NIO.2 review of java

Following on from java IO and NIO, review NIO.2. !!

IO : https://qiita.com/liguofeng29/items/e08dc21b16c0057f601e NIO : https://qiita.com/liguofeng29/items/c827af3d62f219e17755

What is NIO.2?

Simply put, it is an improvement over the existing NIO.

  1. Enhanced FileIO
  2. Enhanced IO based on asynchronous Channle

FileIO enhancement

Core API

API name Overview
Path Represents a platform-independent route
Paths Path utility class
(For Path instance acquisition(get)Was only a method)
Files File utility class

Chat: Paths and Files follow java's consistent naming conventions.

Path, Paths

Path sample(I wanted to get it with markdown)


private static void showPath(Path path) {
    System.out.println("|Acquisition contents|result|");
    System.out.println("|---|---|");
    System.out.printf("|%s | %s |\r\n", "Element count", path.getNameCount());
    System.out.printf("|%s | %s |\r\n", "Specified element name", path.getName(0));
    System.out.printf("|%s | %s |\r\n", "file name", path.getFileName());
    System.out.printf("|%s | %s |\r\n", "File system name", path.getFileSystem());
    System.out.printf("|%s | %s |\r\n", "parent", path.getParent());
    System.out.printf("|%s | %s |\r\n", "root", path.getRoot());
    System.out.printf("|%s | %s |\r\n", "Is it an absolute pass?", path.isAbsolute());
}

Path,Paths


private static void path_test() {
    //Relative path
    Path relativePath = Paths.get(".", "NIO2", "sub", "nio2-file.txt");
    System.out.println("----Relative path----");
    showPath(relativePath);
    //Absolute path
    System.out.println("----Absolute path----");
    showPath(relativePath.toAbsolutePath());
}
Acquisition contents result
Element count 4
Specified element name .
file name nio2-file.txt
File system name sun.nio.fs.WindowsFileSystem@6e0be858
parent .\NIO2\sub
root null
Is it an absolute pass? false
Acquisition contents result
Element count 8
Specified element name workspace
file name nio2-file.txt
File system name sun.nio.fs.WindowsFileSystem@6e0be858
parent C:\workspace\git\java-projects\java-sample.\NIO2\sub
root C:\
Is it an absolute pass? true
  1. The result to be obtained differs depending on the absolute path and relative path.
  2. sun.nio.fs.WindowsFileSystem, which makes __ "platform independent" __?
  3. Get a Path instance from Paths # get (__File to Path, Path to File is also possible __)

Files

Files sample

nio2-src.txt


1st line, AIC
Second line, UTF-8?
3rd line

Files sample(I wanted to get it with markdown)


private static void testFiles(Path path) {
    System.out.println("|Acquisition contents|result|");
    System.out.println("|---|---|");
    try {
        System.out.printf("|%s | %s |\r\n", "Is it a directory?", Files.isDirectory(path));
        System.out.printf("|%s | %s |\r\n", "Hidden", Files.isHidden(path));
        System.out.printf("|%s | %s |\r\n", "Is it a directory?", Files.isWritable(path));
        System.out.printf("|%s | %s |\r\n", "The size is", Files.size(path));
        System.out.printf("|%s | " , "Get file contents");
        Files.lines(path).forEach(line -> {
            System.out.printf("%s<br>" , line);
        });
        System.out.printf("|\r\n");
        System.out.printf("|%s | " , "Get directory elements");
        Files.list(path.getParent()).forEach(p -> {
            System.out.printf("%s<br>" , p);
        });
        System.out.printf("|\r\n");
        System.out.printf("|%s | %s |\r\n", "Storage capacity", Files.getFileStore(path).getTotalSpace() / 1024 / 1024 / 1024 + "GB");
        System.out.printf("|%s | %s |\r\n", "Available capacity", Files.getFileStore(path).getUsableSpace() / 1024 / 1024 / 1024 + "GB");
        System.out.printf("|%s | %s |\r\n", "Unallocated capacity", Files.getFileStore(path).getUnallocatedSpace() / 1024 / 1024 / 1024 + "GB");
        System.out.printf("|%s | %s |\r\n", "Does it exist", Files.exists(path));
        Files.delete(path);
        System.out.printf("|%s | %s |\r\n", "delete", "Deleted");
        System.out.printf("|%s | %s |\r\n", "Does it exist", Files.exists(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Acquisition contents result
Is it a directory? false
Hidden false
Is it a directory? true
The size is 64
Get file contents 1st line, AIC
Second line, UTF-8?
3rd line
Get directory elements .\NIO2\nio2-desc.txt
.\NIO2\nio2-src.txt
.\NIO2\sub
Storage capacity 111GB
Available capacity 54GB
Unallocated capacity 54GB
Does it exist true
delete Deleted
Does it exist false

File#WalkTree With existing IO, I had to implement recursive scanning myself, and the code was complicated and not easy to use.

In 1.7, Files # walkFileTree allows recursive scanning.

callback Overview
preVisitDirectory Occurs before directory access
visitFile Occurs before directory access
visitFileFailed Occurs before directory access
postVisitDirectory Occurs after directory access
FileVisitResult Overview
CONTINUE continue
SKIP_SIBLINGS After continuing, the corresponding file,Do not scan directory siblings
SKIP_SUBTREE After continuing, the corresponding file,Do not scan the child hierarchy of directory
TERMINATE walk(scanning)To quit

There were samples of walkFileTree here and there, so I'll omit them!

Files#walk In 1.8, Files # walk is convenient!

Files.walk


Files.walk(Paths.get(".", "NIO2"), FileVisitOption.FOLLOW_LINKS)
    //Swap directory and file
    .sorted(Comparator.reverseOrder())
    //Confirmation of deletion target
    .peek(System.out::println)
    //Delete
    .forEach(path -> {
        try {
            Files.delete(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    });

Other

WatchService It is a mechanism to monitor File changes. In the traditional way, possible implementations

  1. Launch another thread
  2. Save the state
  3. Scan at regular intervals and compare with the previous state

You can easily create files with WatchService.

WatchService sample


try {
    WatchService watchService = FileSystems.getDefault().newWatchService();
    Paths.get(".").register(
        watchService,
        StandardWatchEventKinds.ENTRY_CREATE, //CREATE monitor
        StandardWatchEventKinds.ENTRY_DELETE, //DELETE monitoring
        StandardWatchEventKinds.ENTRY_MODIFY  //MODIFY monitoring
    );
    System.out.println("-----watch start-----");
    while (true) {
        //Keep waiting
        WatchKey key = watchService.take();
        key.pollEvents().stream()
            .forEach(
                watchEvent -> {
                    System.out.println("Type of occurrence: " + watchEvent.kind().name());
                    System.out.println("Target name: " + watchEvent.context());
                });
        //Next monitoring
        if (!key.reset()) {
            break;
        }
    }
} catch (IOException | InterruptedException e) {
    e.printStackTrace();
}
  1. Generate WatchService
  2. Register WatchService and monitor contents
  3. Get WatchKey
  1. Processing
  2. WatchKey reset

Attribute read / write

Roughly, it is an implementation of FileAttributeView, and it seems that you can operate detailed attributes.

BasicFileAttributeView sample


Path path = Paths.get(".", "NIO2", "nio2-src.txt");

BasicFileAttributeView view = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes attributes = view.readAttributes();

System.out.println("Last access: " + attributes.lastAccessTime());
System.out.println("Latest correction time: " + attributes.lastModifiedTime());

Recommended Posts

NIO.2 review of java
NIO review of java
Review of java Shilber
Java NIO 2 review notes
Java review
Java IO review
[Java] Overview of Java
Predicted Features of Java
[Java] Significance of serialVersionUID
java --Unification of comments
Java inner class review
History of Java annotation
java (merits of polymorphism)
A quick review of Java learned in class
Review Java annotations now
Review java8 ~ Lambda expression ~
[Java] Three features of Java
Summary of Java support 2018
Java review ③ (Basic usage of arrays / reference type)
A quick review of Java learned in class part4
[Java] About Objects.equals () and Review of String comparisons (== and equals)
A quick review of Java learned in class part3
A quick review of Java learned in class part2
[Java] Mirage-Basic usage of SQL
[Java] Beginner's understanding of Servlet-②
[Java] Practice of exception handling [Exception]
Basics of character operation (java)
Progate Java (Beginner) Review & Summary
[Java] Creation of original annotation
4th day of java learning
[Java] Beginner's understanding of Servlet-①
Java end of month plusMonths
Java Collections Framework Review Notes
[Java] Summary of regular expressions
[Java] Summary of operators (operator)
[Java] Implementation of Faistel Network
[Java] Comparator of Collection class
Summary of Java language basics
[Java] Summary of for statements
Summary of Java Math class
Enumeration of all combinations Java
java (inheritance of is-a principle)
Implementation of gzip in java
Advantages and disadvantages of Java
Benefits of Java static method
[Java] Summary of control syntax
Implementation of tri-tree in Java
Summary of java error processing
[Java] Summary of design patterns
[Java] Summary of mathematical operations
Review of Ruby basic grammar
[Java] Speed comparison of string concatenation
Think of a Java update strategy
[Java] Delete the elements of List
[For beginners] Summary of java constructor
Various methods of Java String class
Root cause of java framework bugs
About fastqc of Biocontainers and Java
[Java version] The story of serialization
Summary of [Java silver study] package
About Lambda, Stream, LocalDate of Java8