当前位置: 代码迷 >> 综合 >> Java8【从无到有从有到无】【F2】文件操作
  详细解决方案

Java8【从无到有从有到无】【F2】文件操作

热度:37   发布时间:2024-02-12 18:44:27.0

1.文件操作

文件路径为绝对路径

 

1.1.按字节读取文件

byte[] contentBytes = Files.readAllBytes(Paths.get(fileName));
Files.write(Paths.get(fileName_target), contentBytes, StandardOpenOption.CREATE);

1.2.按行读取文件

List<String> contentLines = Files.lines(Paths.get(fileName)).collect(java.util.stream.Collectors.toList());
contentLines.forEach(System.out::println);
Files.write(Paths.get(fileName_target1), contentLines, Charset.defaultCharset(), StandardOpenOption.CREATE);

1.3.newBufferedWriter和newBufferedReader读写文件

Path filePath = Paths.get(fileName_target2);
if(!Files.exists(filePath)) {try {Files.createFile(filePath);} catch (IOException e) {e.printStackTrace();}
}BufferedWriter bfw = Files.newBufferedWriter(filePath);
bfw.write("Files类的API:newBufferedWriter");
bfw.flush();
bfw.close();Files.write(Paths.get(fileName_target2), "Hello".getBytes());BufferedReader bfr = Files.newBufferedReader(filePath);
System.out.println(bfr.readLine());
bfr.close();

1.4.遍历文件和目录

Files.list(Paths.get(path)).forEach(System.out::println);
对于比较大文件夹,使用DirectoryStream 会性能更好
Files.newDirectoryStream(Paths.get(path)).forEach(System.out::println);

1.5.遍历出目录中的文件

Files.list(Paths.get(path)).filter(Files::isRegularFile).forEach(System.out::println);

1.6.遍历出隐藏文件

final File[] files = new File(path).listFiles(file->file.isHidden());
for(File file:files){System.out.println(file.getName());
}