Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

15.9. Files

15.9.1. Files.lines

	
			
@Test
void testReadFile2() throws IOException {
   String fileName = "D:\\test\\netkiller\\neo.txt";

   // 读取文件内容到Stream流中,按行读取
   Stream<String> lines = Files.lines(Paths.get(fileName));

   // 随机行顺序进行数据处理
   lines.forEach(line -> {
      System.out.println(line);
   });
}		
			
			
			
// 按文件行顺序进行处理
lines.forEachOrdered(System.out::println);

// 利用CPU多和的能力,进行数据的并行处理parallel(),适合比较大的文件。
lines.parallel().forEachOrdered(System.out::println);			
			
			

15.9.2. Files.readAllLines

			
@Test
void testReadFile3() throws IOException {
   String fileName = "D:\\test\\netkiller\\neo.txt";

   // 转换成List<String>, 要注意java.lang.OutOfMemoryError: Java heap space
   List<String> lines = Files.readAllLines(Paths.get(fileName),
               StandardCharsets.UTF_8);
   lines.forEach(System.out::println);

}			
			
			

15.9.3. Files.readAllBytes

			
@Test
void testReadFile5() throws IOException {
   String fileName = "D:\\test\\netkiller\\neo.txt";

   //如果是JDK11用上面的方法,如果不是用这个方法也很容易
   byte[] bytes = Files.readAllBytes(Paths.get(fileName));

   String content = new String(bytes, StandardCharsets.UTF_8);
   System.out.println(content);
}			
			
			

15.9.4. Files.newBufferedReader

			
@Test
void testReadFile6() throws IOException {
   String fileName = "D:\\test\\netkiller\\neo.txt";

   // 带缓冲的流读取,默认缓冲区8k
   try (BufferedReader br = new BufferedReader(new FileReader(fileName))){
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
   }

   //java 8中这样写也可以
   try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))){
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
   }

}			
			
			

15.9.5. Files.delete

			
Files.delete(file.toPath());			
			
			

boolean delete = file.delete(); 传统delete返回false/true没有返回失败原因,而Files则会给出“文件占用/文件不存在/删除目录非空”等原因,同时会抛出异常

			
public class Test {
    public static void main(String[] args) throws IOException {
        File dir = new File("d:\\test");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File("d:\\test\\a.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        new FileInputStream(file);

        boolean delete = file.delete();
        System.out.println(delete ? "删除成功!" : "删除失败!");     
    }
}