Working with the Path Class

Source: Internet
Author: User

The content in this section is from Pro Java 7 nio.2, which is a type of Path, which is a category in the Nio.2, and is compared with the convenience of using the java.io in the conventional system, and is organized as follows:

    • Defining a path & getting info about a path

From the following program and output, to explain the use of the Path category.

1  PackageIdv.steven.nio2.path;2 3 ImportJava.nio.file.Path;4 Importjava.nio.file.Paths;5 6  Public classNormalize {7 8      Public Static voidMain (string[] args) {9String filename = "D:/english/./esl/business/esl Podcast 165-a Practical Joke.mp3";TenPath path1 =paths.get (filename). normalize (); One System.out.println (path1.tostring ()); A          -Path path2 =paths.get (filename); - System.out.println (path2.tostring ()); the          -System.out.println (System.getproperty ("User.home")); -          -System.out.println ("Root of this path:" +path1.getroot ()); +System.out.println ("Parent:" +path1.getparent ()); -          +System.out.println ("Number of the name elements in path:" +Path1.getnamecount ()); A          at          for(inti = 0; I < Path1.getnamecount (); i++) { -System.out.println ("Name element" + i + "is:" +Path1.getname (i)); -         } -          -System.out.println ("Subpath (0,3):" + Path1.subpath (0, 3)); -          inSystem.out.println ("Filename:" +path1.getfilename (). toString ()); -     } to}

The results are as follows:

D:\English\ESL\Business\ESL Podcast 165-a practical joke.mp3d:\english\. \esl\business\esl Podcast 165-a Prac Tical Joke.mp3c:\users\stevenroot of this path:d:parent:d:\english\esl\businessnumber of the name elements in Path:4name el Ement 0 is:englishname element 1 is:eslname element 2 is:businessname element 3 Is:esl Podcast 165-a practical Joke. Mp3subpath (0,3): English\esl\businessfilename:esl Podcast 165-a Practical Joke.mp3

The categories provided in the java.io, for the files in the file system, are referred to by the program developers through the process string, so that you can see that the program will inevitably appear in many ways, the name of the method or category, Path directly provides the method that these program developers need, Eliminates the difficulty of repeating the wheel. Then the following is stated:

      1. Normailize: Remove the "surplus" part, what is the excess? In the above program, path1 and Path 2, path1 have call Normailize, remove the second line of red, the result of the output is simpler, actually pointing to the same file.
      2. Home directory: The user's home record, as shown in line 16th of the program, because I tested in Windows 7, the result is C:\users\Steven, if it is tested in Linux, it might be/home/steven.
      3. Root directory: The 18th line of the program, get the root of the record, the above program to see, of course, is d:\.
      4. Parent directory: The 19th line of the program can be recorded on the previous layer, thus getting D:\English\ESL\Business.
      5. Break full file name: The 21st to 27th line of the program is to explain how to break down the full file name, and the previous practice might use string[] folder = Filename.split ("/"); This way, now the Path type directly provides this function, 21 lines is to return the total number of records (including the file name), 23~25 line will be output to the console. The subpath in line 27th is a method provided by the Path category that allows the program developers to easily get the parts needed for the full file name.
      6. File name: line 29th is the way to get the file name.
    • Ignore symbol link
1  PackageIdv.steven.nio2.path;2 3 Importjava.io.IOException;4 Importjava.nio.file.LinkOption;5 ImportJava.nio.file.Path;6 Importjava.nio.file.Paths;7 8  Public classConvert {9 Ten      Public Static voidMain (string[] args)throwsIOException { One         //String filename = "c:/java/jdk1.7.0_67/readme.html"; AString filename = "d:/readme.html"; -Path PATH =paths.get (filename). normalize (); -System.out.println ("Path:" +path); theSystem.out.println ("Path:" +Path.toabsolutepath ()); -SYSTEM.OUT.PRINTLN ("Real path:" +Path.torealpath (linkoption.nofollow_links)); -     } -}

There's a readme.html file under c:/java/jdk1.7.0_67, and we're in d:/. Set up a shortcut to that file, and then if the following program is accessed using Toabsolutepath and Torealpath, it will find that when the Torealpath is accessed, the exception is thrown out, as shown in the following code (under Linux, Symbol L Ink) is not an authentic file. This result will allow us to ignore the path in the record when we access all the files under a certain target.

Path:d:\readme.htmlpath:d:\readme.htmlexception in thread "main" java.nio.file.nosuchfileexception:d:\ Readme.htmlat sun.nio.fs.WindowsException.translateToIOException (windowsexception.java:79) at Sun.nio.fs.WindowsException.rethrowAsIOException (windowsexception.java:90) at Sun.nio.fs.WindowsLinkSupport.getRealPath (windowslinksupport.java:259) at Sun.nio.fs.WindowsPath.toRealPath ( windowspath.java:836) at Sun.nio.fs.WindowsPath.toRealPath (windowspath.java:44) at Idv.steven.nio2.path.Convert.main (CONVERT.JAVA:16)
    • Comparing paths

Sometimes, the full file name of the two files is different, but it actually refers to the same file, when you use the Path category, can you compare it? Check the program ...

1  PackageIdv.steven.nio2.path;2 3 Importjava.io.IOException;4 ImportJava.nio.file.Files;5 ImportJava.nio.file.Path;6 Importjava.nio.file.Paths;7 8  Public classCompare {9 Ten      Public Static voidMain (string[] args) { OneString filename1 = "D:/english/./esl/business/esl Podcast 165-a Practical Joke.mp3"; AString filename2 = "/english/./esl/business/esl Podcast 165-a Practical Joke.mp3"; -          -Path path1 =Paths.get (filename1); thePath path2 =Paths.get (filename2); -          -         if(Path1.equals (path2)) { -System.out.println ("Equal"); +         } -         Else { +SYSTEM.OUT.PRINTLN ("Not Equal"); A         } at          -         intCompare =Path1.compareto (path2); - System.out.println (compare); -          -         Try { -             BooleanCheck =files.issamefile (path1, path2); in             if(check) { -System.out.println ("The paths locate the same file!");//true to}Else { +System.out.println ("The paths does not locate the same file!"); -             } the         }  *         Catch(IOException e) { $ System.out.println (E.getmessage ());Panax Notoginseng         } -     } the}

The above program filename1 and filename2 are the same file, we first use equals and compareTo to compare, but can not get the correct results! As follows:

Not equal-24the paths Locate the same file!

Why would it be like this? Because of the comparison of equals, it is object.equals in the Path category, and, of course, path1 and path2 are not the same two objects, they pass back false. So what is the comparison of CompareTo? It is compared in the Order of the dictionary, only when the two files are written exactly the same, will be transferred back 0 means the same, when the first is greater than the second, the return of the positive integer, the first is smaller than the second time the negative integer. It is important to note that CompareTo has different responses in different operating systems, such as Windows, because the Windows file name is not the size of the case, so it is not in the size of the case, in Linux because the file name is divided into size, it will be in the size of the comparison. The 28th line of the program is the correct comparison method, only this method will get the results we really want!

Working with the Path Class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.