Java nio 16, Java NiO Files

Source: Internet
Author: User
Tags parent directory

Last update: 2015-04-15

This Java NIO files Class (Java.nio.file.Files) provides several methods for manipulating files in a file system. This Java NIO files Class tutorial will cover the use of most common methods of these methods. This class contains many methods, so you can also check the Javadoc if you need a method that is not described here. This files class is just possible for it to still have a method.

This java.nio.file.Files works with Java.nio.file.Path instances so that you need to understand the path class before you work with the files class.

Files.exists ()

This method checks whether the given path is in this file.

It is possible to create a path instance that does not exist on the file system. For example, if you plan to create a new directory, you will first create the corresponding path instance and then create the directory.

Because the path instance may or may not point to the existence of the file system, you can use the Files.exists () method to decide if they are (once you need to check that).

Here is a Java files.exists () instance:

Path PATH = Paths.get ("Data/logging.properties"); Boolean pathexists =        files.exists (path,            new linkoption[]{ Linkoption.nofollow_links});

This example first creates an instance of path to this path, and we check to see if he exists. Second, this example calls the Files.exists () method using the path instance as the first argument.

Note the second parameter of files.exists. This parameter is an array option that affects how the files.exists determines whether a file path exists. In the above example, this array includes this linkoption.nofollow_links, which means that the Files.exists method should not follow the symbolic link of the filesystem to determine if the path exists.

Files.createdirectory ()

This method creates a new directory from the path instance. Here's an 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 WRO ng    E.printstacktrace ();}


The first line creates a path instance of a directory that will be created. This files.createdirectory () method inside the Try-catch block uses this path as a parameter to be called. If a directory is created successfully, an instance of path that executes the newly created path is returned.

If this directory already exists, a java.nio.file.FileAlreadyEXistsException will be thrown. If other errors occur, a IOException may be thrown, for example, if the desired parent directory does not exist, a ioexception will be thrown. This parent directory is the new directory that you want to create. Therefore, it means the parent directory of this new directory.

Files.copy ()

This method copies a file from one path to another. Here's an 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, this example creates a path instance of source and destination. The example then calls the Files.copy () method, which takes the two path instances as arguments. This will cause the file reference to be copied to the file reference of the directory path through the source path.

If the destination file already exists, a java.nio.file.FileAlreadyEXistsException will be thrown. If something else is wrong, a ioexception will be thrown. For example, if the directory where the files are copied does not exist, a ioexception will be thrown.

Overwrite files that already exist

Forcing the files.copy () to overwrite the already existing file is possible. Here's an example of how to overwrite an existing file with the Files.copy () method:

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

Note the third parameter in the Files.copy () method. This parameter indicates that the destination file will be overwritten if it already exists.

Files.move ()

This Java NiO class also contains a function that moves a file from one path to another. Moving a file is just like renaming it, moving a file to a different directory, and changing his name at the same time. Yes, this java.io.File class Renameto () method can do the same thing, but now you can also do the file movement function in the Java.nio.file.Files class.

Here's an 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 ();}

The source path and destination path are created first. This source path points to the file that will be moved, and the entire destination path points to where the file will be moved. The Files.move method is then called. This will cause the file to be moved.

Note the third parameter in this method, which tells the method that it will overwrite any file that exists in the destination path. This parameter is actually selectable.

A IOException exception may be thrown if a file failure is moved. For example, if a file already exists in the destination path, and you omit the standardcopyoption.replace_existing option, or the file that will be moved does not exist, and so on.

Files.delete ()

This method can delete a file or a directory. Here's an example:

Path PATH = Paths.get ("data/subdir/logging-moved.properties"); try {    files.delete (path);} catch (IOException e) {    //deleting file failed    e.printstacktrace ();}

Start by creating a path instance that points to the file you want to delete. Then call this method of deletion. If the deletion fails for some reason (for example, a file or directory does not exist), a IOException will be thrown.

Files.walkfiletree ()

This method includes the ability to recursively traverse a directory tree. This method carries a path instance and filevisitor as a parameter. This path instance points to the directory you want to traverse. This filevisitor is called during traversal.

Before I explain how this traversal works, there is a Filevisitor interface first:

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 into the Walkfiletree method. Each method that your filevisitor implements will be called at different times during the directory traversal. If you do not want to implement all of these methods, you can inherit the Simplefilevisitor class, which contains the default implementations of all the methods of the Filevisitor interface.

Here is an example of a walkfiletree:

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

In each method implemented by Filevisitor, different times during the directory traversal will be called:

This preVisitDirectory() method will be called before any directories are accessed. This postVisitDirectory() method is called after the directory is accessed.

This visitfile () method is called during every file access, and it is not called for the directory--it's just relative to the file. This visitfilefailed () method will be called once it fails to access the file. For example, if you don't have the right permissions, or something else goes wrong.

Each of the four methods returns an FileVisitResult enumeration instance. This enumeration instance contains the following four options:

    • CONTINUE
    • TERMINATE
    • Skip_siblings
    • Skip_subtree
Use the returned value to determine how the next method should go. Continue means that the file will continue to be accessed normally. Terminate means that the access to this file will now be terminated. Skip_siblings means that the access to this file will continue, but will not access the file or the sibling node of the directory. Skip_subtree means that the access to this file will continue, but will not access entries for this directory. This value is only if the preVisitDirectory() Return will have this function. If returned from any other method, he will be interpreted as a continue to be used.
Search for FilesHere is a Walkfiletree method, which inherits the SimpleFileVisitor To find the README.txt file:
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 { C3/>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 ();}

recursive removal of directoriesThe Walkfiletree method can also be used to delete a directory of all files and subdirectories within it. If it is empty, this files.delete () method will simply delete a directory. By traversing all the directories and deleting all the files (in Visitfile ()) in each directory, and after deleting the directory itself (inpostvisitdirectory () inside), you can delete a directory with all subdirectories and files. Here is an example of a recursive delete directory:
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 classThis java.nio.file.Files class contains a number of other useful features, such as the ability to create symbolic links, the ability to determine file size, the ability to set file permissions, and so on. You can check out this class of Java documentation to get more information on these methods.

Translation Address: http://tutorials.jenkov.com/java-nio/files.html

Java nio 16, Java NiO Files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.