Detailed explanation of of based on the usage of java Files and Paths classes

  • 2020-11-26 18:45:56
  • OfStack

The IO file in Java7 has changed a lot. Many new classes have been introduced specifically:


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;

. And so on, to replace the original IO based file java.io.File operation.

Path is the replacement for File

A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter.

Path is used to represent file paths and files. There are several ways to construct an Path object to represent a file path, or a file:

1) First, two static methods of final class Paths, how to construct Path object from 1 path string:


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);

2) FileSystems structure:


Path path3 = FileSystems.getDefault().getPath("C:/", "access.log");

3) Conversion between File and Path, conversion between File and URI:


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

4) Create a file:


Path target2 = Paths.get("C:\\mystuff.txt");
//   Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-rw-rw-");
//   FileAttribute<Set<PosixFilePermission>> attrs = PosixFilePermissions.asFileAttribute(perms);
try {
  if(!Files.exists(target2))
Files.createFile(target2);
} catch (IOException e) {
  e.printStackTrace();
}

PosixFilePermission is not supported under windows to specify rwx permissions.

5) ES49en. newBufferedReader Read file:


try {
//      Charset.forName("GBK")
      BufferedReader reader = Files.newBufferedReader(Paths.get("C:\\my.ini"), StandardCharsets.UTF_8);
      String str = null;
      while((str = reader.readLine()) != null){
        System.out.println(str);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

You can see that using ES54en. newBufferedReader is much easier than the original FileInputStream, then BufferedReader packaging, etc.

Here, if the specified character encoding is incorrect, an exception MalformedInputException may be thrown, or a garbled code may be read:


java.nio.charset.MalformedInputException: Input length = 1
  at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
  at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
  at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
  at java.io.InputStreamReader.read(InputStreamReader.java:184)
  at java.io.BufferedReader.fill(BufferedReader.java:161)
  at java.io.BufferedReader.readLine(BufferedReader.java:324)
  at java.io.BufferedReader.readLine(BufferedReader.java:389)
  at com.coin.Test.main(Test.java:79)

6) Document writing operation:


try {
  BufferedWriter writer = Files.newBufferedWriter(Paths.get("C:\\my2.ini"), StandardCharsets.UTF_8);
  writer.write(" Test the file write operation ");
  writer.flush();
  writer.close();
} catch (IOException e1) {
  e1.printStackTrace();
}

7) Traverse a folder:


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

try (Stream<Path> stream = Files.list(Paths.get("C:/"))){
      Iterator<Path> ite = stream.iterator();
      while(ite.hasNext()){
        Path pp = ite.next();
        System.out.println(pp.getFileName());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

Above is traversing a single directory, it does not traverse the entire directory. To traverse the entire directory, use: Files.walkFileTree

8) Traverse the entire file directory:


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);
0

Here's a practical example:


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);
1

The directory below all eligible pictures deleted: filePath. matches (". * _ [1 | 2] {1} \ \. (the & # 63; i)(jpg|jpeg|gif|bmp|png)")


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);
2

Generates thumbnails of specified size for all images in the directory. a.jpg generates a_1.jpg

2. Strong java. nio. file. Files

1) Create directories and files:


try {
  Files.createDirectories(Paths.get("C://TEST"));
  if(!Files.exists(Paths.get("C://TEST")))
  Files.createFile(Paths.get("C://TEST/test.txt"));
//  Files.createDirectories(Paths.get("C://TEST/test2.txt"));
} catch (IOException e) {
  e.printStackTrace();
}

Note that creating directories and files Files.createDirectories and ES109en.createFile cannot be mixed. You must have a directory before you can create files in a directory.

2) File copying:

Copy from file to file: ES115en.copy (Path source, Path target, CopyOption options);

Copy from input stream to file: ES125encopy (InputStream in, Path target, CopyOption options);

Copy from file to output stream: ES135en.copy (Path source, OutputStream out);


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);
4

3) Iterate through 1 directory and folder as described above: Files.newDirectoryStream, Files.walkFileTree

4) Read file properties:


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);
5

5) Read and set file permissions:


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);
6

The Files class is simply a powerful 1 mess, with almost all file and directory related properties and operations supported by the desired api. I won't bother to go any further here; see the documentation for jdk8 for details.

1 practical example:


Path path = Paths.get("C:/", "Xmp");
    Path path2 = Paths.get("C:/Xmp");
    
    URI u = URI.create("file:///C:/Xmp/dd");    
    Path p = Paths.get(u);
7

Scenario is that sql server export data, will datatime guide into hexadecimal binary format, such as:, CAST (0 x0000A2A500FC2E4F AS DateTime))

So the above procedure is the last one will be exported datatime field, CAST (0 x0000A2A500FC2E4F AS DateTime) delete, generate new value of a field does not contain datetime sql scripts. Used to import into mysql.

In fact, there is a better way to do it halfway. Using sql yog can flexibly import the table and data in sql server into mysql. Using sql server's built-in ability to export data can be tricky.


Related articles: