Java 7 NIO Files, Path operation file

Keywords: Java encoding socket Programming

From Java 1.0 to 1.3, we face the following problems when developing applications that require I/O support:

  • Without the concept of data buffers or channels, developers have to program to deal with many of the underlying details.
  • I/O operations are blocked and scalability is limited
  • The supported character set encoding is limited and requires a lot of manual encoding to support specific types of hardware.
  • Regular expressions are not supported and data processing is difficult.

To solve these problems, NIO was introduced in Java 1.4. There are two major improvements:

  • Introducing non-blocking I/O in Java 1.4
  • Modification of non-blocking I/O in Java 7

Since then, Java has abstracted buffers and channels for I/O operations; the encoding and decoding capabilities of character sets; provided interfaces for mapping files to memory data; the ability to implement non-blocking I/O; and regular expression class libraries based on popular Perl implementations.

NIO has taken Java a big step forward, but I/O programming remains a challenge for developers, especially for files and directories. To overcome these limitations, NIO.2 API is provided in Java 7. It has three objectives:

  • A File System Interface that can acquire file attributes in batches and introduce service provider interface implemented by standard file system
  • Provide a socket and file that can be asynchronous
  • Complete the socket-channel function defined in JSR-51, including additional support for binding, option configuration and multicast datagrams.

Path: Usually represents the location in the file system.

  1. Create a Path

    Path path1 = Paths.get("D:\\test\\test1"); // Equivalent to Path path1 = FileSystems. getDefault (). getPath ("D:\\ test");
  2. Getting information from Path

    We can get information from Path, such as its parent directory, filename, etc.

    System.out.println("fileName : " + path1.getFileName()); // Get the file name
    System.out.println("number of name elements : " + path1.getNameCount()); // Gets the number of name elements
    System.out.println("parent path : " + path1.getParent());
    System.out.println("root of path : " + path1.getRoot());
    System.out.println("subpath from root, 2 elements deep : " + path1.subpath(0, 2)); // Get subpaths between elements 0-2
  3. NIO.2 Path and Existing FIle Classes in Java

    Classes in the new API can completely replace the old java.io.File-based API. But we inevitably have to interact with a lot of legacy I/O code. Java 7 offers two new approaches:

    • A new toPath() method is added to the java.io.File class to convert existing Files into new Paths.
    • The Path class has a toFile() method that converts an existing Path to File
    File file = new File("D:\\test");
    Path path3 = file.toPath(); // file to path
    path3.toAbsolutePath();
    file = path3.toFile(); // path to file
  4. Find files in directories

    Let's start with a simple example of filtering out all. txt and. jpg files in the current directory with matching patterns. This is the ability to handle a single directory.

    Path path4 = Paths.get("D:\\test");
    
    DirectoryStream<Path> stream = Files.newDirectoryStream(path4, "*.{txt,jpg}"); // Declare filtered streams, matching patterns as glob pattern matching
    for (Path entry : stream) {
        System.out.println(entry.getFileName());
    }
  5. Traversing the Catalog Tree

    Java 7 supports traversal of the entire directory tree. That is to say, we can easily search the files in the directory tree, find them in subdirectories, and perform operations on them.

    Path path5 = Paths.get("F:\\test\\demo"); // Setting the Start Directory
    Files.walkFileTree(path5, new FindJavaVisitor()); // Key method
    
    private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
        // SimpleFileVisitor can do most of the work, such as traversing directories. The only thing we need to do is rewrite the visitFile() method.
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            if (file.toString().endsWith(".java")) {
                System.out.println(file.getFileName());
            }
            return FileVisitResult.CONTINUE;
        }
    }

    Files: Let's make it easy to copy, move, delete, or process files with all the tools we need.

  6. Create and delete files

    Path path6 = Paths.get("D:\\backup\\test.txt");
    Files.createFile(path6); // To create a file, make sure that D:\backup exists
    Files.delete(path6);
  7. Copying and Moving of Files

    Path sourcePath7 = Paths.get("D:\\test\\test.txt");
    Path targetPath7 = Paths.get("D:\\backup\\test.txt");
    Files.copy(sourcePath7, targetPath7, StandardCopyOption.REPLACE_EXISTING); // REPLACE_EXISTING Overlay Replaces Existing Files
    Files.move(sourcePath7, targetPath7, StandardCopyOption.REPLACE_EXISTING);
  8. Properties of files

    Path path8 = Paths.get("D:\\test");
    System.out.println(Files.getLastModifiedTime(path8));
    System.out.println(Files.size(path8));
    System.out.println(Files.isSymbolicLink(path8));
    System.out.println(Files.isDirectory(path8));
    System.out.println(Files.readAttributes(path8, "*")); // Get all attributes of a file
  9. Quick Reading and Writing Data

    Java 7 can provide as many auxiliary methods as possible for reading and writing file contents.
    Of course, these new methods use Path, but they can also interoperate with stream-based classes in the java.io package. So we can read all the lines or all the bytes in the file in one way.

    // Java 7 can open files directly with a buffer reader and writer or an input-output stream (to be compatible with previous Java I/O codes).
    BufferedWriter writer = Files.newBufferedWriter(path9, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
    writer.write("Hello world...");
    writer.flush();
    writer.close();
    
    BufferedReader reader = Files.newBufferedReader(path9, StandardCharsets.UTF_8);
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    
    // Simplified read and write
    
    List<String> lines = Files.readAllLines(path9, StandardCharsets.UTF_8);
    for (String line1 : lines) {
        System.out.println(line1);
    }
    
    byte[] bytes = Files.readAllBytes(path9); // Read file byte stream
    System.out.println(new String(bytes, StandardCharsets.UTF_8));
    
    Files.write(path9, bytes); // Write file byte stream

    Previously, it was difficult to read and write files. Is it very convenient to use NIO of Java 7?

Reference Content: The Way to Practice Java Programmers

Posted by kaedus on Sun, 23 Dec 2018 03:54:05 -0800