Java NIO Files

 

Jakob Jenkov
Last update: 2015-04-15

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAABpElEQVRIx2NgwAOUlZWVFBUVqxQUFPYC8XMg/gvFIPZekBxIDQOpQAkIgAashhr2nwAGqVkN0kOU4UBXxQA1fCbCYHT8GaSXkOFlZBiMgkFm4HM5RYYjWYLqE2iYkxMsOIMLJU6gEUqqIaCUdB1PQlgNT4rYFAG9uRVXqgHKpejp6TFBfa8BFJsPpEHx9xtZHTgJQ9M5hkEqKipyQLkkIPs7mtxM9PizsLBgAloQBZR7jObIKgZoJsKwAKjBCOpCNSB/KcwioKYIbIkEKLceizl7GaBhiS0lLNXS0mKCGaCmpsYDtMwO6G05HBZgSyTPGXBFEtAgI3V1dS5iMqeqqqoIrvjCaQEQzyW2aAH6NgSfBc9xSILioQIYTByELACq3Y4rKeOMZGg81BEyHOgIFzx5ZS/OZIqEF4LiA4fhckD5p3gcWIUro4GS5FsgPg5UVASMRC4shpsA5R/iK8bhdQWWogJkwUSgIXrIhurr64MylBkoAaDlWtxFBRGF3Xsgvgwtd4gtED9jVEA0La6RLKFdhYPmE9pUmWhxQptKHxlQo9kCAHsFA8aGHksTAAAAAElFTkSuQmCC" alt="" /> aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAABEklEQVRIx2NgwAOUlZWVFBUVqxQUFPYC8XMg/gvFIPZekBxIDQOpQAkIgAashhr2nwAGqVkN0kOU4UBXxQA1fCbCYHT8GaSXkOFlZBiMgkFm4HM5RYYjWYLqE2iYkxMsOIMLJU6gEYpL8XcoJtWS1fCkiCe1fAfKy4AwGZb8BSdhaDr/TwMLQHFRxQDNRP9pEEQgvJcBmitxKkKKp/9IKa5bTU2NT0VFRQoovh+P/ucMhHIrNguABosAg00MmgJ18MUDWRYA2beB+D6IbW1tzUTIApKDCCbX0tLChMzHFUR7aWjBXkLJlCILwMmUQEajBP+F1xUEigpy8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PkgOJxOIIrBygvQ2SRUYU1o+no6HABJaNwWQBNWQTDH15XoBcVQENKgEHEAmQvRdO0E5iTBYD0ZiIsWE2osFsIilCggTpAl9gAg8UEaHEAUPw4EYZ/xqiAaFpc06XCoUuVSZdKHxlQo9kCAHcMPgoKWH+jAAAAAElFTkSuQmCC" alt="" /> aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAABqUlEQVRIx71WwUrDQBANEqQnP6AUSZo0JDnkByLSU/HkB0g/o0jJVUrx5MGvkHxDzuKxZ/HgoeQsOXiQom9kVjbJZhON7cKDbDI7M/vezG4MQzMcxxnbtp1YlpUBObBj0HNG38jG+O0YY8BBys4+W0A2Ka3p5BxZzbGg6OC4ioLWtjm//oPjEsiHLvNezqUg5Z0w5zVa4jg2XdcdYsEM81vgtStdJU1Y0JphdZdBEJgIdtUxUPpTippquYfDJZKZknMRCLs6wbeHtur6LmGu8y7bzmG78DzvWNLtrkWLxOAmUhog01PKHs8rYMvvNzK/LTvJDO5KpYHM/2QyGSCjNdO5FUGYriZNckPXrcQ/VZDv+6ZEy5zXbARdLLxSB20ACc9wciYFWXMCC5qHYXjUsIudliLgA3gC3oB3EYToYk1yUV3cJ0qKGkUGzZdcyiMO8iLoQrAbtpnyfKYUWVemURQNpGp5ZFouuPvPhU4s9lBZprpGg8GKgtBOmC56n7DDkWhGmtOxomw03VHRE2nrYdcDRe0C2utxfZAL5yBXZkWT/Vz68viP35Yv1q4mS+AFuV8AAAAASUVORK5CYII=" alt="" />

The Java NIO Files class (java.nio.file.Files) provides several methods for manipulating files in the file system. This Java NIO Files tutorial will cover the most commonly used of these methods. The Files class contains many methods, so check the JavaDoc too, if you need a method that is not described here. The Files class just might have a method for it still.

The java.nio.file.Files class works with java.nio.file.Path instances, so you need to understand the Pathclass before you can work with the Files class.

这个FIles类和Path类一起合作,你最好先了解一下Path类。FIles类有很多方法,你可以查javaDoc

Files.exists()

检查你创建的Path是否存在

The Files.exists() method checks if a given Path exists in the file system.

It is possible to create Path instances that do not exist in the file system. For instance, if you plan to create a new directory, you would first create the corresponding Path instance, and then create the directory.

Since Path instances may or may not point to paths that exist in the file system, you can use the Files.exists() method to determine if they do (in case you need to check that).

Here is a Java Files.exists() example:

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

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

This example first creates a Path instance pointing to the path we want to check if exists or not. Second, the example calls the Files.exists() method with the Path instance as the first parameter.

Notice the second parameter of the Files.exists() method. This parameter is an array of options that influence how the Files.exists() determines if the path exists or not. In this example above the array contains the LinkOption.NOFOLLOW_LINKS which means that the Files.exists() method should not follow symbolic links in the file system to determine if the path exists.

注意第二个参数,是一个数组,检查的条件

 LinkOption.NOFOLLOW_LINKS 不遵循符号连接

Files.createDirectory()

创建path路径,存在的话会报错。

The Files.createDirectory() method creates a new directory from a Path instance. Here is a Java Files.createDirectory() example:

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();
}

The first line creates the Path instance that represents the directory to create. Inside the try-catch block the Files.createDirectory() method is called with the path as parameter. If creating the directory succeeds, a Path instance is returned which points to the newly created path.

If the directory already exists, a java.nio.file.FileAlreadyExistsException will be thrown. If something else goes wrong, an IOException may get thrown. For instance, if the parent directory of the desired, new directory does not exist, an IOException may get thrown. The parent directory is the directory in which you want to create the new directory. Thus, it means the parent directory of the new directory.

Files.copy()

拷贝方法,从一个文件拷到另外一个文件,目标文件存在会报错

The Files.copy() method copies a file from one path to another. Here is a Java NIO Files.copy() example:

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();
}

First the example creates a source and destination Path instance. Then the example calls Files.copy(), passing the two Path instances as parameters. This will result in the file referenced by the source path to be copied to the file referenced by the destination path.

If the destination file already exists, a java.nio.file.FileAlreadyExistsException is thrown. If something else goes wrong, an IOException will be thrown. For instance, if the directory to copy the file to does not exist, an IOException will be thrown.

Overwriting Existing Files

注意后面的那个参数,替换已存在

It is possible to force the Files.copy() to overwrite an existing file. Here an example showing how to overwrite an existing file using Files.copy():

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();
}

Notice the third parameter to the Files.copy() method. This parameter instructs the copy() method to overwrite an existing file if the destination file already exists.

Files.move()

移动一个文件并修改名称,第三个参数替换已存在

The Java NIO Files class also contains a function for moving files from one path to another. Moving a file is the same as renaming it, except moving a file can both move it to a different directory and change its name in the same operation. Yes, the java.io.File class could also do that with its renameTo() method, but now you have the file move functionality in the java.nio.file.Files class too.

Here is a Java Files.move() example:

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();
}

First the source path and destination path are created. The source path points to the file to move, and the destination path points to where the file should be moved to. Then the Files.move() method is called. This results in the file being moved.

Notice the third parameter passed to Files.move() . This parameter tells the Files.move() method to overwrite any existing file at the destination path. This parameter is actually optional.

The Files.move() method may throw an IOException if moving the file fails. For instance, if a file already exists at the destination path, and you have left out the StandardCopyOption.REPLACE_EXISTING option, or if the file to move does not exist etc.

Files.delete()

删掉一个文件

The Files.delete() method can delete a file or directory. Here is a Java Files.delete() example:

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

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

First the Path pointing to the file to delete is created. Second the Files.delete() method is called. If the Files.delete() fails to delete the file for some reason (e.g. the file or directory does not exist), an IOExceptionis thrown.

Files.walkFileTree()

遍历一个目录

The Files.walkFileTree() method contains functionality for traversing a directory tree recursively. The walkFileTree() method takes a Path instance and a FileVisitor as parameters. The Path instance points to the directory you want to traverse. The FileVisitor is called during traversion.

Before I explain how the traversal works, here is first the FileVisitor interface:

public interface FileVisitor {

    public FileVisitResult preVisitDirectory(
Path dir, BasicFileAttributes attrs) throws IOException; public FileVisitResult visitFile(
Path file, BasicFileAttributes attrs) throws IOException; public FileVisitResult visitFileFailed(
Path file, IOException exc) throws IOException; public FileVisitResult postVisitDirectory(
Path dir, IOException exc) throws IOException { }

You have to implement the FileVisitor interface yourself, and pass an instance of your implementation to the walkFileTree() method. Each method of your FileVisitor implementation will get called at different times during the directory traversal. If you do not need to hook into all of these methods, you can extend the SimpleFileVisitor class, which contains default implementations of all methods in the FileVisitor interface.

Here is a walkFileTree() example:

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;
}
});

Each of the methods in the FileVisitor implementation gets called at different times during traversal:

The preVisitDirectory() method is called just before visiting any directory. The postVisitDirectory() method is called just after visiting a directory.

The visitFile() mehtod is called for every file visited during the file walk. It is not called for directories - only files. The visitFileFailed() method is called in case visiting a file fails. For instance, if you do not have the right permissions, or something else goes wrong.

Each of the four methods return a FileVisitResult enum instance. The FileVisitResult enum contains the following four options:

  • CONTINUE
  • TERMINATE
  • SKIP_SIBLINGS
  • SKIP_SUBTREE

By returning one of these values the called method can decide how the file walk should continue.

CONTINUE means that the file walk should continue as normal.

TERMINATE means that the file walk should terminate now.

SKIP_SIBLINGS means that the file walk should continue but without visiting any siblings of this file or directory.文件遍历继续,但是不要访问其他兄弟节点

SKIP_SUBTREE means that the file walk should continue but without visiting the entries in this directory. This value only has a function if returned from preVisitDirectory(). If returned from any other methods it will be interpreted as a CONTINUE.文件遍历继续,但是不要访问这个文件的条目,这个只有在pre方法中返回。其他方法的话意味着继续

Searching For Files

上面的方法的具体实例,找一个文件名为README.txt 的文件

Here is a walkFileTree() that extends SimpleFileVisitor to look for a file named 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();
}

Deleting Directories Recursively

循环删除文件和文件夹

The Files.walkFileTree() can also be used to delete a directory with all files and subdirectories inside it. The Files.delete() method will only delete a directory if it is empty. By walking through all directories and deleting all files (inside visitFile()) in each directory, and afterwards delete the directory itself (inside postVisitDirectory()) you can delete a directory with all subdirectories and files. Here is a recursive directory deletion example:

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();
}

Additional Methods in the Files Class

FIles类还有很多其他的方法哦,大家查可以看源代码查看方法。如:创建符号连接,查看文件大小,设置文件权限等方法。

The java.nio.file.Files class contains many other useful functions, like functions for creating symbolic links, determining the file size, setting file permissions etc. Check out the JavaDoc for thejava.nio.file.Files class for more information about these methods.

Java NIO Files的更多相关文章

  1. java nio Files.newDirectoryStream用法

    try(DirectoryStream<Path> dirStream = Files.newDirectoryStream(Paths.get(directory,"*.ts& ...

  2. Java NIO学习系列七:Path、Files、AsynchronousFileChannel

    相对于标准Java IO中通过File来指向文件和目录,Java NIO中提供了更丰富的类来支持对文件和目录的操作,不仅仅支持更多操作,还支持诸如异步读写等特性,本文我们就来学习一些Java NIO提 ...

  3. Java NIO 完全学习笔记(转)

    本篇博客依照 Java NIO Tutorial翻译,算是学习 Java NIO 的一个读书笔记.建议大家可以去阅读原文,相信你肯定会受益良多. 1. Java NIO Tutorial Java N ...

  4. Java NIO 学习总结 学习手册

    原文 并发编程网(翻译):http://ifeve.com/java-nio-all/  源自 http://tutorials.jenkov.com/java-nio/index.html Java ...

  5. 海纳百川而来的一篇相当全面的Java NIO教程

    目录 零.NIO包 一.Java NIO Channel通道 Channel的实现(Channel Implementations) Channel的基础示例(Basic Channel Exampl ...

  6. Java NIO Path

    Java NIO Path Creating a Path Instance Creating an Absolute Path Creating a Relative Path Path.norma ...

  7. Java NIO Path接口和Files类配合操作文件

    Java NIO Path接口和Files类配合操作文件 @author ixenos Path接口 1.Path表示的是一个目录名序列,其后还可以跟着一个文件名,路径中第一个部件是根部件时就是绝对路 ...

  8. JAVA NIO学习四:Path&Paths&Files 学习

    今天我们将学习NIO 的最后一章,前面大部分涉及IO 和 NIO 的知识都已经讲过了,那么本章将要讲解的是关于Path 以及Paths 和 Files 相关的知识点,以对前面知识点的补充,好了言归正传 ...

  9. Java NIO之拥抱Path和Files

    Java面试通关手册(Java学习指南)github地址(欢迎star和pull):https://github.com/Snailclimb/Java_Guide 历史回顾: Java NIO 概览 ...

随机推荐

  1. VMware虚拟机上配置nginx后,本机无法访问问题

    nginx装在CentOS上,用本机访问虚拟机的时候却出现了不能访问的问题,查了资料以后,原来是防火墙的问题.具体情况如下:防火墙可以ping通虚拟机,虚拟机也可以ping通防火墙.接着检查了服务器端 ...

  2. 【Fiddler学习】Fiddler面板的详细介绍(转)

    转自:https://www.cnblogs.com/GreenLeaves/p/6971452.html 下面开始分析主界面的功能区: 1.Fiddler菜单栏,上图黑色部分,包括捕获http请求, ...

  3. 【Linux】【secureCRT】下载,安装,激活攻略

    以前公司使用的是SSH访问Linux服务器,今天争取了能看到数据,问了同事使用的是secureCRT,然后自己就装了一个. 下载地址:https://www.vandyke.com/download/ ...

  4. SLD Related Gateway Serivces Unavaliable

    SAP NW 7.4 default switched on the ACL (access control list) in gateway service, so only local acces ...

  5. mysql source 命令导入不了sql!

    sql文件也是正常, 为什么就是导入不了呢?? 后面才发现,可能是编码被notepad++ 修改了—— 一看发现是UTF-8 无BOM,改回UTF-8格式编码 就正常了!! 虽然看到的都是正常汉字, ...

  6. MFC相关函数汇总(持续汇总跟新中)

    最近有一项关于MFC的任务,做完后总结了一些使用的函数,希望对大家有帮助,也是怕自己忘了所以就写了这篇博客,方便后续的工作. 1,FindWindow() 获得窗口句柄: 2,GetWindowRec ...

  7. java的原子类 AtomicInteger 实现原理是什么?

    采用硬件提供原子操作指令实现的,即CAS.每次调用都会先判断预期的值是否符合,才进行写操作,保证数据安全. CAS机制 CAS是英文单词Compare And Swap的缩写,翻译过来就是比较并替换. ...

  8. addEventListener 的事件冒泡

    语法 target.addEventListener(type, listener, useCapture); target 文档节点.document.window 或 XMLHttpRequest ...

  9. AIR程序调用本地默认应用程序打开本地文件

    当我用下面语句的时候,可以成功打开桌面文件夹下面的文件: var file:File = File.desktopDirectory.resolvePath("test.jpg") ...

  10. 尚硅谷springboot学习20-web开发简介

    使用SpringBoot 1).创建SpringBoot应用,添加我们需要的模块: 2).SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来 3).自己编写业 ...