Java中如何按行读取文件及一次性全部读取数据呢?
下文笔者讲述使用java代码按行读取文件和一次性读取文件的方法及示例分享,如下所示
读取文件的实现思路
1.一行一行读取文件 使用readLine()方法 2.一次读取全部文件 使用read()方法例:读取文件的示例
一行一行的读取文件 ClassPathResource classPathResource = new ClassPathResource("fileName.txt"); InputStream inputStream =classPathResource.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String txt = ""; while(reader.ready()) { txt += reader.readLine(); } String s = new String(Base64.encodeBase64(txt.getBytes(UTF_8)), UTF_8); 一次性读取文件 private String getFile(String fileName) throws IOException { ClassPathResource classPathResource = new ClassPathResource(fileName); File file = classPathResource.getFile(); FileInputStream in = new FileInputStream(file); byte[] fileContent = new byte[(int) file.length()]; in.read(fileContent); String txt = new String(fileContent); String pileString = new String(Base64.encodeBase64(txt.getBytes(UTF_8)), UTF_8); return pileString; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。