**Java Advanced feature enhancements -NIO

This part of the network has a large number of resources for reference, in this part of the collation and correction, thanks to the predecessors pay, at the end of each section of the article has a list of references ~


GitHub github.com/wangzhiwubi…

Big Data into the Road of God series:

GitHub github.com/wangzhiwubi…

Java Advanced Feature Enhancements – Collection

Java Advanced Feature enhancements – Multithreading

Java advanced features enhancements -Synchronized

Java Advanced feature enhancements – Volatile

Java Advanced Feature Enhancements – Concurrent Collections framework

Java Advanced Features enhancement – Distributed

Java Advanced Feature enhancements -Zookeeper

Java Advanced Features enhancements -JVM

Java Advanced Feature Enhancements -NIO

Write in front of all the characters: the author in this special recommend Google ranked first on the NIO: tutorials.jenkov.com/java-nio/in… Although it is in English, it is not difficult to read. The author will translate this series of articles if you are very popular.

Java NIO embraces Path and Files

File I/O cornerstone: Path

File IO has changed a lot in Java7, with the introduction of a number of new classes to replace the original java.io.File based File IO operations:

import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; DE...Copy the code

We’ll look at the Path class in the following ways:

  • Create a Path
  • Conversion between File and Path, conversion between File and URI
  • Get information about Path
  • Remove redundant items from the Path

You can create an instance of a Path using the Get () method of the Paths utility class:

// Use absolute Path Path = paths.get ("c:\\data\\myfile.txt"); // Use the relative Path Path = paths.get ("/home/jakobjenkov/myfile.txt");
Copy the code

The following is equivalent to the above:

Path path = FileSystems.getDefault().getPath("c:\\data\\myfile.txt");
Copy the code

2 Conversion between File and Path and between File and URI

        File file = new File("C:/my.ini");
        Path p1 = file.toPath();
        p1.toFile();
        file.toURI();
Copy the code

3 Obtain information about Path

// Use the get() method of the Paths tool class to create Path = paths.get ("D:\\XMind\\bcl-java.txt");
       System.out.println("File name:" + path.getFileName());
       System.out.println("Number of name elements:" + path.getNameCount());
       System.out.println("Parent path:" + path.getParent());
       System.out.println("Root path:" + path.getRoot());
       System.out.println("Is it an absolute path?"+ path.isAbsolute()); // The startsWith() method can take either a string or a Path object system.out.println ("Is it possible to start with a given path D: :" + path.startsWith("D:\\")); System.out.println("String form of the path:" + path.toString());
Copy the code

Results:

Name: bcl-java.txt Number of name elements: 2 Parent path: D:\XMind Root path: D:\ Whether absolute path:trueWhether to start with a given path D:trueThe path has the string form: D:\XMind\bcl-java.txtCopy the code

Sometimes there may be one or two points in the Path we need to deal with

  • . Indicates the current directory
  • . Indicates the parent directory or the upper level directory:

Here is an example of how to use the normalize() and toRealPath() methods of the Path class. And.. Get rid of.

  • Normalize () : Returns a path that removes redundant name elements.
  • ToRealPath () : a blend of the toAbsolutePath() and Normalize () methods
Path currentDir = paths.get ("."); System.out.println(currentDir.toAbsolutePath()); // output C:\Users\Administrator\NIODemo\. Path currentDir2 = paths.get (".\\NIODemo.iml");
        System.out.println("Original path format:"+currentDir2.toAbsolutePath());
        System.out.println("After normalize () :"+currentDir2.toAbsolutePath().normalize());
        System.out.println("After executing the toRealPath() method:+currentDir2.toRealPath()); / /.. Path currentDir3 = paths.get ("..");
        System.out.println("Original path format:"+currentDir3.toAbsolutePath());
        System.out.println("After normalize () :"+currentDir3.toAbsolutePath().normalize());
        System.out.println("After executing the toRealPath() method:+currentDir3.toRealPath());
Copy the code

Results:

C:\Users\Administrator\NIODemo\. Original path format: C:\Users\Administrator\NIODemo\.\NIODemo. Iml After normalize () : Iml :\Users\Administrator\NIODemo\ niodemo. iml :\Users\Administrator\NIODemo\NIODemo. Iml :\Users\Administrator\NIODemo. C:\Users\Administrator\NIODemo\.. After normalize () : C:\Users\Administrator After toRealPath() : C:\Users\AdministratorCopy the code

! [d6a70ed9337b5e22fa34de22f36236b4] (Java NIO the embrace of the Path and Files d6c a0 e6cacd6 resources / 1-76-4-8 e05 – C1D9353E293A. PNG)

Embrace the class Files

The Files class (java.nio.file.files) in Java NIO provides a variety of methods for manipulating Files in a file system. This tutorial covers most of these methods. The Files class contains a number of methods, so you can query the JavaDoc documentation directly if not covered in this article. The java.nio.file.Files class is used in conjunction with java.nio.file.Path

1 Check whether the specified Path exists in the file system. Run files.exists () to check whether the file Path exists.

       Path path = Paths.get("D:\\XMind\\bcl-java.txt"); boolean pathExists = Files.exists(path, new LinkOption[]{LinkOption.NOFOLLOW_LINKS}); System.out.println(pathExists); //true
Copy the code

Notice the second argument to files.exists (). It is an array, and this parameter directly affects how files.exists () determines whether a path exists. In this case, the array contains linkoptions.nofollow_links, which means no symbolic link files are detected.

2 Create a file or folder

CreateFile: createFile with files.createfile () :

        Path target2 = Paths.get("C:\\mystuff.txt");
        try {
            if(! Files.exists(target2)) Files.createFile(target2); } catch (IOException e) { e.printStackTrace(); }Copy the code

Create folder:

  • Create a folder with files.createDirectory ()
  • Create a folder with files.createDirectories ()

Files.createdirectories () will first createDirectories by creating all non-existent parent directories, while files.createdirectory () just creates directories and will report an error if its parent directory does not exist. For example, the following program is created using files.createDirectory (). This is because I don’t have a data folder on drive D.

    Path path = Paths.get("D://data//test");
    try {
        Path newDir = Files.createDirectories(path);
    } catch(FileAlreadyExistsException e){
        // the directory already exists.
    } catch (IOException e) {
        //something else went wrong
        e.printStackTrace();
    }
Copy the code

You can delete a file or directory by using the files.delete () method:

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

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

You can copy a file from one address to another using the files.copy () method

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

Copy can also force an existing target file to be overwritten by changing the copy() method above to the following format:

    Files.copy(sourcePath, destinationPath,
            StandardCopyOption.REPLACE_EXISTING);
Copy the code

5 Obtain the file attributes

        Path path = Paths.get("D:\\XMind\\bcl-java.txt");
        System.out.println(Files.getLastModifiedTime(path));
        System.out.println(Files.size(path));
        System.out.println(Files.isSymbolicLink(path));
        System.out.println(Files.isDirectory(path));
        System.out.println(Files.readAttributes(path, "*"));
Copy the code

Results:

2016-05-18T08:01:44Z
18934
false
false{lastAccessTime = 2017-04-12 T01: well. 149351 Z, lastModifiedTime = 2016-05-18 T08:01:44 Z, size = 18934, CreationTime = 2017-04-12 T01: pleased. 149351 z, isSymbolicLink =false, isRegularFile=true, fil
Copy the code

6 Walk through a folder

        Path dir = Paths.get("D:\\Java");
        try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)){
            for(Path e : stream){
                System.out.println(e.getFileName());
            }
        }catch(IOException e){

        }
Copy the code

Results:

Eclipse Intellij IDEA Jar JDK MarvenRespository MyEclipse 2017 CI Nodejs RedisDesktopManager Solr - 7.2.1Copy the code

The above is traversing a single directory, it does not traverse the entire directory. To traverse the entire directory, use the files.walkfiletree ().files.walkfiletree () method to recursively traverse the directory.

WalkFileTree accepts a Path and FileVisitor as arguments. The Path object is the directory to traverse, and FileVistor is called on each traverse. FileVisitor needs to be implemented by the caller and passed as a parameter to walkFileTree(). Each method of FileVisitor is called multiple times during the traversal. If you don’t need to deal with every method, then you can inherit its default implementation class, SimpleFileVisitor, which has all interfaces implemented empty.

public class WorkFileTree {
    public static void main(String[] args) throws IOException{
        Path startingDir = Paths.get("D: \ \ apache tomcat - - 9.0.0 M17." ");
        List<Path> result = new LinkedList<Path>();
        Files.walkFileTree(startingDir, new FindJavaVisitor(result));
        System.out.println("result.size()=" + result.size());
    }

    private static class FindJavaVisitor extends SimpleFileVisitor<Path>{
        private List<Path> result;
        public FindJavaVisitor(List<Path> result){
            this.result = result;
        }
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs){
            if(file.toString().endsWith(".java")){
                result.add(file.getFileName());
            }
            returnFileVisitResult.CONTINUE; }}}Copy the code

The above example outputs my D:\apache-tomcat-9.0.0.M17, which is the number of files ending in.java in my Tomcat installation directory. Results:

result.size()=4
Copy the code

The Files class is really powerful. In addition to these operations, there are many other operations such as reading and setting file permissions, updating file owners, and so on.

Reference Documents:

  • Official JDK documentation
  • # 1 Java NIO tutorial in Google search
  • The Java Programmer’s Way
  • The Official Java 8 Programming Reference Tutorial (Version 9)
  • File manipulation is new in Java7

Please stamp: making the original https://github.com/wangzhiwubigdata/God-Of-BigData pay close attention to the public, push, interview, download resources, focus on more big data technology ~ data into the way of god ~ update is expected to 500 + articles, has been updated 50 + ~Copy the code