原博客地址:https://blog.youkuaiyun.com/LuoZheng4698729/article/details/51697648
Path 类是jdk7新增加的特性之一,用来代替java.io.File类。
之所以新增这个类,是由于java.io.File类有很多缺陷:
1.java.io.File类里面很多方法失败时没有异常处理,或抛出异常
java.io.File.delete()方法返回一个布尔值指示成功或失败但是没有失败原因
2.Path 速度快,方便。
Path 操作
1.删除文件
2.遍历目录,不包括子目录的文件
Path dir = Paths.get("F:\\LZ\\pdf");
DirectoryStream<Path> stream = Files.newDirectoryStream(dir);
for(Path path : stream){
System.out.println(path.getFileName());
}
- 1
- 2
- 3
- 4
- 5
2.遍历目录,及其子目录下的文件
Path dir = Paths.get("F:\\LZ\\pdf");
Files.walkFileTree(dir,new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
if(file.toString().endsWith(".pdf")){
System.out.println(file.getFileName());
}
return super.visitFile(file, attrs);
}
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
3.创建多级目录
Path dir = Paths.get("F:\\LZ\\xx\\dd");
Files.createDirectories(dir);
- 1
- 2
4.创建文件, 不存在则抛出异常
Path dir = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
Files.createFile(dir);
- 1
- 2
5.文件的复制
Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
Path target = Paths.get("F:\\LZ\\xx\\dd\\2.txt");
//REPLACE_EXISTING:文件存在,就替换
Files.copy(src, target,StandardCopyOption.REPLACE_EXISTING);
- 1
- 2
- 3
- 4
- 5
6.一行一行读取文件
Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
BufferedReader reader = Files.newBufferedReader(src,StandardCharsets.UTF_8);
String line ;
while((line=reader.readLine()) != null){
System.out.println(line);
}
reader.close();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
7.写入字符串
Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
BufferedWriter writer = Files.newBufferedWriter(src, StandardCharsets.UTF_8
,StandardOpenOption.APPEND); // 追加
writer.write("hello word Path");
writer.close();
- 1
- 2
- 3
- 4
- 5
8.二进制 读写 与字符串类似
- 一个方法直接去取字符串 和 二进制流
// 字符串
Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
for(String line : Files.readAllLines(src)){
System.out.println(line);
}
// 二进制流
byte[] bytes = Files.readAllBytes(src);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
10.监测是否 目录下的 文件,目录 被修改,创建,或删除.
11.读取文件的 最后 1000 个字符