Java8读文件方法代码学习

时间:2022-04-29
本文章向大家介绍Java8读文件方法代码学习,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Java8读文件方法代码学习

  JDK7中引入了新的文件操作类java.nio.file.File,它包含了很多有用的方法来操作文件,比如检查文件是否为隐藏文件,或者是检查文件是否为只读文件。开发者还可以使用Files.readAllBytes(Path)方法把整个文件读入内存,此方法返回一个字节数组,还可以把结果传递给String的构造器,以便创建字符串输出。

  此方法确保了当读入文件的所有字节内容时,文件属性是关闭的,否则就会出现IO异常或其它的未检查异常。这意味着在读文件到最后的块内容后,无需关闭文件。要注意,此方法不适合读取很大的文件,因为可能存在内存空间不足的问题。开发者还应该明确规定文件的字符编码,以避免任异常或解析错误。

  如果你想读入文件作为字符串,那么你还可以使用readAllLines(Path path, Charset cs)方法,此方法与之前的方法相似,也是在读完文件后无需关闭文件。但是它返回的不是字节数组,而是字符串数组。而且,Java8重写了此方法,无需指定字符集,直接使用UTF-8编码进行字符串转换。 如果你想一行一行的读入文件作为字符串,那么你可以使用Files.lines()方法,它会从读入的文件中返回字符串流,并使用UTF-8编码把字节转换成字符。使用forEach()方法,可以只用一行Java代码实现把文件的所有内容输出到控制台,如下面第三个代码片段。

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
  
public class FileReadingTest {
 public static void main(String[] args) throws IOException {
  // Java 7 例子
  // Files.readAllBytes默认以UTF-8编码读入文件,故文件的编码如果不是UTF-8,那么中文内容会出现乱字符
  System.out.println(new String(Files.readAllBytes(Paths.get("D:\jd.txt"))));
   // Java 8例子
  List<string> <span id="4_nwp" style="width: auto; height: auto; float: none;"><a id="4_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=11&jk=bcb3fb28d19226b9&k=line&k0=line&kdi0=0&luki=4&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=b92692d128fbb3bc&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0" target="_blank" mpid="4" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">line</span></a></span>s = Files.readAllLines(Paths.get("D:\jd.txt"), StandardCharsets.UTF_8);
  StringBuilder sb = new StringBuilder();
  for(String line : lines){
   sb.append(line);
  }
  String <span id="5_nwp" style="width: auto; height: auto; float: none;"><a id="5_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=11&jk=bcb3fb28d19226b9&k=from&k0=from&kdi0=0&luki=1&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=b92692d128fbb3bc&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0" target="_blank" mpid="5" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">from</span></a></span>File = sb.toString();
        System.out.println(fromFile);
  
 }
}</string>

  如果使用的不是JDK7,而是JDK8,那么一行代码即可完成读文件。

import static <span id="3_nwp" style="width: auto; height: auto; float: none;"><a id="3_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=11&jk=bcb3fb28d19226b9&k=java&k0=java&kdi0=0&luki=6&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=b92692d128fbb3bc&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0" target="_blank" mpid="3" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">java</span></a></span>.lang.System.out;
import static java.nio.file.Files.readAllBytes;
import static java.nio.file.Paths.get;
  
import java.io.IOException;
public class FileIntoString {
 public static void main(String[] args) throws IOException {
  // 一行代码搞定读文件,默认是UTF-8编码
  out.println(new String(readAllBytes(get("d:/jd.txt"))));
 }
}

  如果使用JDK8,那么还可以使用流API来读写文件,这样代码更简洁、高效。下面的例子中,lines()方法返回字符串流,字符串使用的是UTF-8编码。如下:

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
  
  
public class Java8FileReader {
 public static void main(String[] args) throws IOException {
  // Java8用流的方式读文件,更加高效
  Files.<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=11&jk=bcb3fb28d19226b9&k=line&k0=line&kdi0=0&luki=4&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=b92692d128fbb3bc&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F6039%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">line</span></a></span>s(Paths.get("D:\jd.txt"), StandardCharsets.UTF_8).forEach(System.out::println);
 }
}

  上面的例子要注意几点:

  1)文件可能很大,可能会超出内存空间,使用前要做评估。

  2)要输出日志,记录为什么无法读取文件或者在阅读文件时遇到的任何错误。

  3)在把字节转换成字符时,应该指定字符编码。

  4)要处理文件不存在的情况。

  还要注意,如果读入的文件的编码是ANSI编码,那么上面的例子在读取文件内容时会报java.nio.charset.MalformedInputException: Input length = 1错误。