java读取文件(更新jdk7及jdk8)
以字节的方式读取:
InputStream inputStream = new FileInputStream(file); int temp = -1; StringBuilder sb = new StringBuilder(); while((temp = inputStream.read()) != -1){ sb.append((char)temp); } inputStream.close();
也可以多个字节一起读取:
InputStream inputStream = new FileInputStream(file); byte[] bytes = new byte[10]; StringBuilder sb = new StringBuilder(); int length = -1; while((length = inputStream.read(bytes))!= -1){ sb.append(new String(bytes,0,length,Charset.forName("utf-8"))); } inputStream.close();
以字符的方式读取:
InputStream inputStream = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(inputStream,Charset.forName("utf-8")); StringBuilder sb = new StringBuilder(); int temp = -1; while((temp = (isr.read()))!= -1){ sb.append((char)temp); } inputStream.close(); isr.close();
或者用封装的BufferedReader按行读取,效率更高:
InputStream inputStream = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(inputStream,Charset.forName("utf-8")); BufferedReader bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line = null; while((line = bufferedReader.readLine())!=null){ sb.append(line + '\n'); } inputStream.close(); isr.close(); bufferedReader.close();
-----------------------------------------------以上是jdk7之前一般使用的读取文件方法-------------------------------------------------------------------------------------------------------
jdk7引入了新的文件api: java.nio.file.Files。 Files.readAllBytes()方法将文件内容全部读入内存,并且确保读取完之后文件是关闭的,也就是说,不用手动调用close方法:
String path = "C:\\test.txt";
System.out.print(Files.readAllBytes(Paths.get(path)));
当文件过大时,不建议使用readAllBytes()方法将文件内容一次全部读入到内存里面。
java8中使用流的方式来读取更高效:
Files.lines(Paths.get(path),StandardCharsets.UTF_8).forEach(System.out::println);