New feature of java--path

Keywords: Java Oracle encoding

The Path class is one of the new features added to jdk7 to replace the java.io.File class.  
The reason for adding this class is that the java.io.File class has many shortcomings:
1. Many methods in the java.io.File class fail without exception handling or throwing an exception.
The java.io.File.delete() method returns a Boolean value indicating success or failure but without cause of failure.

2.Path is fast and convenient.


Original address: http://blog.csdn.net/LuoZheng4698729/article/details/51697648

Path operation

1. Delete files
 
2. Traversing directories, excluding subdirectories

    Path dir = Paths.get("F:\\LZ\\pdf");
    DirectoryStream<Path> stream = Files.newDirectoryStream(dir);
    for(Path path : stream){
        System.out.println(path.getFileName());
    }
  • 1
  • 2
  • 3
  • 4
  • 5

2. Traversing directories and files in their subdirectories

    Path dir = Paths.get("F:\\LZ\\pdf");
    Files.walkFileTree(dir,new SimpleFileVisitor<Path>(){
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            if(file.toString().endsWith(".pdf")){
                System.out.println(file.getFileName());
            }
            return super.visitFile(file, attrs);
        }
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3. Create multilevel directories

    Path dir = Paths.get("F:\\LZ\\xx\\dd");
    Files.createDirectories(dir);
  • 1
  • 2

4. Create a file and throw an exception if it does not exist

    Path dir = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    Files.createFile(dir);
  • 1
  • 2

5. File duplication

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    Path target = Paths.get("F:\\LZ\\xx\\dd\\2.txt");

    //REPLACE_EXISTING: Files exist and are replaced
    Files.copy(src, target,StandardCopyOption.REPLACE_EXISTING);
  • 1
  • 2
  • 3
  • 4
  • 5

6. Read files line by line

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    BufferedReader reader = Files.newBufferedReader(src,StandardCharsets.UTF_8);
    String line ;
    while((line=reader.readLine()) != null){
        System.out.println(line);
    }
    reader.close();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

7. Write strings

    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    BufferedWriter writer = Files.newBufferedWriter(src, StandardCharsets.UTF_8
            ,StandardOpenOption.APPEND); // Append
    writer.write("hello word Path");
    writer.close();
  • 1
  • 2
  • 3
  • 4
  • 5

8. Binary reads and writes are similar to strings

  1. A method to extract strings and binary streams directly
    // Character string
    Path src = Paths.get("F:\\LZ\\xx\\dd\\1.txt");
    for(String line : Files.readAllLines(src)){
        System.out.println(line);
    }
    // Binary stream
    byte[] bytes = Files.readAllBytes(src);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

10. Monitor whether files in directories are modified, created, or deleted.

11. Read the last 1000 characters of the file


Original address: http://blog.csdn.net/zpf336/article/details/45074445
Official API: http://docs.oracle.com/javase/7/docs/api/

Official documents: http://docs.oracle.com/javase/7/docs/index.html

When I learned how to use Lucene 5.0, I found that I could not click on Path at any point. Later, I found something inside JDK7 on the internet. Then I went to get Path objects myself, but I didn't know how to get Path. So I went to find out how to get Path. I found this article, demonstrated it in person, and published it in the hope that it would be helpful.

Examples are as follows:

  1. package com.darren.test.jdk7;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.IOException;  
  6. import java.nio.charset.Charset;  
  7. import java.nio.file.FileSystems;  
  8. import java.nio.file.Files;  
  9. import java.nio.file.Path;  
  10. import java.nio.file.Paths;  
  11.   
  12. /** 
  13.  * Path It is an important entry point for file operations in the nio.file package of Java 1.7. As a basis, it is necessary to understand 
  14.  */  
  15. public class PathTest {  
  16.     public static void main(String[] args) {  
  17.         //Get path method 1, F:/test/jdk7/test.txt  
  18.         Path path = FileSystems.getDefault().getPath("F:/test/jdk7""test.txt");  
  19.         //Number of Node Layers where Printed Files Are Located  
  20.         System.out.println(path.getNameCount());  
  21.   
  22.         //Get path method 2 and get Path objects by File's toPath() method  
  23.         File file = new File("F:/test/jdk7/test.txt");  
  24.         Path pathOther = file.toPath();  
  25.         //0, indicating that the two path s are equal  
  26.         System.out.println(path.compareTo(pathOther));  
  27.   
  28.         //Obtaining path method 3  
  29.         Path path3 = Paths.get("F:/test/jdk7""test.txt");  
  30.         System.out.println(path3.toString());  
  31.   
  32.         // join two paths  
  33.         Path path4 = Paths.get("F:/test/jdk7");  
  34.         System.out.println("path4: " + path4.resolve("test.txt"));  
  35.         System.out.println("--------------Dividing line---------------");  
  36.   
  37.         try {  
  38.             if (Files.isReadable(path)) {  
  39.                 //Note that the charset parameter of newBufferedRead here throws an exception if it does not correspond to the encoding of the file to be read  
  40.                 //New features of java that do not shut down streams by themselves  
  41.                 BufferedReader br = Files.newBufferedReader(path, Charset.defaultCharset());  
  42.                 // new BufferedReader(new FileReader(new File("F:/test/jdk7/test.txt")));  
  43.                 String line = "";  
  44.                 while ((line = br.readLine()) != null) {  
  45.                     System.out.println(line);  
  46.                 }  
  47.             } else {  
  48.                 System.err.println("cannot readable");  
  49.             }  
  50.         } catch (IOException e) {  
  51.             System.err.println("error charset");  
  52.         }  
  53.     }  
  54. }  

Operation results:

  1. 3  
  2. 0  
  3. F:\test\jdk7\test.txt  
  4. path4: F:\test\jdk7\test.txt  
  5. --------------Dividing line---------------  
  6. I am Darren  



Posted by coollog on Thu, 16 May 2019 17:25:05 -0700