十六、Java NIO Files

所有文章

https://www.cnblogs.com/lay2017/p/12901123.html

正文

NIO的Files提供了操作系统文件的方法,Files经常和Path协作使用,所以在本文之前了解Path是比较有帮助的。

Files.exists

exists方法用于检测Path是否存在于文件系统中

Path path = Paths.get("data/logging.properties");

boolean pathExists = Files.exists(path, new LinkOption[]{ LinkOption.NOFOLLOW_LINKS});

注意到exists有一个参数LinkOption数组,LinkOption参数用于自定义一些校验文件是否存在的逻辑。

以LinkOption.NOFOLLOW_LINKS为例,有的文件系统支持以链接地址作为目录,那么当Path存在链接地址的时候,将会检测为cannot be detemined,结果返回false。

Files.createDirectory

创建目录

Path path = Paths.get("data/subdir");

try {
    Path newDir = Files.createDirectory(path);
} catch(FileAlreadyExistsException e){
    // the directory already exists.
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}

Files.copy

文件拷贝

Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties");

try {
    Files.copy(sourcePath, destinationPath);
} catch(FileAlreadyExistsException e) {
    //destination file already exists
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}

文件拷贝如何目标文件已经存在会抛出异常,如果你想覆盖目标文件

Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties");

try {
    Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
} catch(FileAlreadyExistsException e) {
    //destination file already exists
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}

Files.move

文件移动,和copy类似

Path sourcePath      = Paths.get("data/logging-copy.properties");
Path destinationPath = Paths.get("data/subdir/logging-moved.properties");

try {
    Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    //moving file failed.
    e.printStackTrace();
}

Files.delete

Path path = Paths.get("data/subdir/logging-moved.properties");

try {
    Files.delete(path);
} catch (IOException e) {
    //deleting file failed
    e.printStackTrace();
}

Files.walkFileTree

walkFileTee用于递归遍历Path,使用方法就是调用walkFileTree,并传入两个参数:

1:path:表示要递归哪个目录

2:FileVisitor:访问者,访问文件(了解一下访问者模式比较容易理解这个点)

示例代码如下

Files.walkFileTree(path, new FileVisitor<Path>() {
  @Override
  public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
    System.out.println("pre visit dir:" + dir);
    return FileVisitResult.CONTINUE;
  }

  @Override
  public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    System.out.println("visit file: " + file);
    return FileVisitResult.CONTINUE;
  }

  @Override
  public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
    System.out.println("visit file failed: " + file);
    return FileVisitResult.CONTINUE;
  }

  @Override
  public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
    System.out.println("post visit directory: " + dir);
    return FileVisitResult.CONTINUE;
  }
});

访问者包含了4个方法:

1)preVisitDirectory:访问前回调

2) visitFile:访问回调

3)visitFileFailed:访问失败回调

4)postVisitDirectory:访问后回调

这四个方法需要你返回FileVisitResult,表示下一步怎么执行,FileVisitResult有几个可选项

1)CONTINUE:继续执行

2)TERMINATE:停止执行

3)SKIP_SIBLINES:跳过同级

4)SKIP_SUBTEE:跳过当前目录的子级

下面是一个用walkFileTree搜索README.txt文件的示例代码

Path rootPath = Paths.get("data");
String fileToFind = File.separator + "README.txt";

try {
  Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
    
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      String fileString = file.toAbsolutePath().toString();
      //System.out.println("pathString = " + fileString);

      if(fileString.endsWith(fileToFind)){
        System.out.println("file found at path: " + file.toAbsolutePath());
        return FileVisitResult.TERMINATE;
      }
      return FileVisitResult.CONTINUE;
    }
  });
} catch(IOException e){
    e.printStackTrace();
}

下面是一个用walkFileTree递归删除文件和目录的示例

Path rootPath = Paths.get("data/to-delete");

try {
  Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      System.out.println("delete file: " + file.toString());
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      Files.delete(dir);
      System.out.println("delete dir: " + dir.toString());
      return FileVisitResult.CONTINUE;
    }
  });
} catch(IOException e){
  e.printStackTrace();
}

Files还包含了很多其它的有用的方法,可以查看java.nio.file.Files的类

猜你喜欢

转载自www.cnblogs.com/lay2017/p/12917752.html