Use of nio.2 in Java 7-the use of the first section of the Path class

Source: Internet
Author: User

The path is part of the file system, and in fact it is the format for storing and organizing media files, usually on one or more hard disk devices, so that it can be easily retrieved. The file system can bejava.nio.file.FileSystems 这个final 类来访问,通常我们用来获取它的实例然后做我们想做的事情。FileSystems 包含下面两个非常重要的方法,还有 newFileSystem() 方法,用来构建一个新的文件系统实例。

    • Getdefault (): This static method returns a default filesystem to jvm--, which is usually the default file system for the operating system.
    • Getfilesystem (URI uri): This static method returns a file system based on a list of available file system providers that can match the URI pattern. The path class can manipulate any type of file system and can use any stored place (Java.nio.file.FileStore This class renders potential storage). Typically, the path class points to the default operating system files, but is completely modular in nio.2-can be in-memory data, on the Internet, in the virtual file system filesystem class implementation, these can all be perfectly nio.2 accepted, nio.2 Provides the functionality of all file systems, and we need to execute them on a file, directory, or link file.

The path class is actually an upgraded version of the Java.io.File class, but the file class has some specific operations, so the file class is not considered an obsolete class, nor does it take him as a hindrance. In addition, in Java 7, these two classes can continue to be used, which means that the two classes can be mixed to get the best API operation. Java 7 provides a very simple API to facilitate the conversion of the two.

This is written in the previous IO operation.

Importnew File ("index.html");

But in Java7, we can write:

Import Java.nio.file.Path; Import  = Paths.get ("index.html");

In conclusion, a path class is a program representation of paths in a file system. Path is basically a string of file paths, and the actual referenced resource may not exist.

Once you have identified where the file system and files or directories are stored, you can create a path instance. Absolute path, relative path, using "." Defines the current path as well as the parent path defined by "..", which contains a file or a directory name, which can be done with the path class. The simplest approach is to use the paths helper class to invoke the Get () method. The following example shows several different ways to define path using the same path. This path is used by default C:\rafaelnadal\tournaments\2009\BNP.txt.

Define an absolute directory

An absolute directory is the directory that contains the root directory and then the next few levels of subdirectories and finally the file name or the last level. You can use the following code to define an absolute directory path class.

Path PATH = Paths.get ("C:/rafaelnadal/tournaments/2009/bnp.txt");

The Get () method also supports splitting paths into pieces. NIO will reorganize the path. Look at the following code:

Path PATH = Paths.get ("c:/rafaelnadal/tournaments/2009", "BNP.txt"= Paths.get ("C:", "rafaelnadal/ tournaments/2009 "," BNP.txt "= Paths.get (" C: "," RafaelNadal "," tournaments "," N "," BNP.txt ");

Defines a relative path relative to the root path

Relative paths are part of a full path, and relative paths are typically used to create Web pages. Relative paths are more extensive than absolute paths. Saving a relative path under the current path usually adds a file delimiter. For example, if the current path is a C drive, the absolute path should be: C:\rafaelnadal\tournaments\2009\BNP.txt

Path PATH = Paths.get ("/rafaelnadal/tournaments/2009/bnp.txt"= Paths.get ("/rafaelnadal", "tournaments/2009 /bnp.txt ");

Define a relative path relative to the working directory

When you define a path relative to the current working directory, the path does not start with a file delimiter. For example, the forward directory is relative to the root directory under the C-disk/ATP directory, then the absolute path is returned according to the following code: C:\ATP\rafaelnadal\tournaments\2009\BNP.txt

Path PATH = Paths.get ("Rafaelnadal/tournaments/2009/bnp.txt"

Defines a path obtained from a URI

In some cases, you need to create a path from the URI, and you can use the Uri.create () method to create a path from the URI based on the specified string.

Import= Paths.get (Uri.create ("File:///rafaelnadal/tournaments/2009/BNP.txt"

You can also use the Filesystems.getdefault (). GetPath () method to define a path class.

  

Import= Filesystems.getdefault (). GetPath ("/rafaelnadal/tournaments/2009", "BNP.txt"= Filesystems.getdefault (). GetPath ("/rafaelnadal/tournaments/2009/bnp.txt"= Filesystems.getdefault (). GetPath ("rafaelnadal/tournaments/2009", "BNP.txt"= filesystems.getdefault ().                         GetPath ("/rafaelnadal/tournaments/./2009", "BNP.txt"). Normalize ();

Get the path to the system's home directory

When you want to get the path to the home directory, you can use the following code:

Path Path = Paths.get (System.getproperty ("User.home"), "Downloads", "Game.exe");

In Windows 7, the path returned isC:\Users\{your user name}\downloads\game.exe,在Linux系统中,则返回/home/{your user name}/downloads/game.exe。

--------------------------------------------------------------------------------------------------------------- -------------

Get information about a path

After you have defined the path object, there is a series of ways to access the file's information. First define a path instance:

Path PATH = Paths.get ("C:", "rafaelnadal/tournaments/2009", "BNP.txt");

Get the name of the file or directory:

// Output:BNP.txt

Get root directory

// Output:c:\

Gets the parent directory of the Path

// output:c:\rafaelnadal\tournaments\2009 System.out.println ("Parent:" + path.getparent ());

Gets the element of the pathname

You can usegetNameCount()方法获取路径层级的个数,然后再使用getName()循环遍历每个元素的名字。

// output:4 System.out.println ("Number of the name elements in path:"+//output:rafaelnadal< C8/>tournaments  BNP.txtfor (int i = 0; i < Path.getnamecount (); i++ ) {   System.out.println ("Name element" + i + "is:" + Path.getname (i));}

Get sub-path

// output:rafaelnadal\tournaments\2009

--------------------------------------------------------------------------------------------------------------- -----------

Conversion of Path

In this section, you will describe how to convert a Path object to a string, URI, absolute path, relative path, and file object.

Define a path instance first:

Path PATH = Paths.get ("/rafaelnadal/tournaments/2009", "BNP.txt");

Converted into a string

// Output: \rafaelnadal\tournaments\2009\bnp.txt String path_to_string = path.tostring (); System.out.println ("Path to String:" + path_to_string);

Convert to a URI

// Output:file: // /c:/rafaelnadal/tournaments/2009/bnp.txt URI Path_to_uri = Path.touri (); System.out.println (

Convert from relative path to absolute path

// Output:c:\rafaelnadal\tournaments\2009\bnp.txt Path Path_to_absolute_path = Path.toabsolutepath (); System.out.println (

Convert to Real path

Import//output:c:\rafaelnadal\tournaments\2009\bnp.txttry  {     = Path.torealpath (linkoption.nofollow_links);     System.out.println ("path to Real path:" +catch  (nosuchfileexception e) {      Catch (IOException e) {     System.err.println (e);}

Convert to File Object

// Output:BNP.txt File path_to_file =//output: \rafaelnadal\tournaments\2009\bnp.txt Path File_to_path = Path_to_file.topath (); System.out.println ("Path to File name:" + path_to_file.getname ()); System.out.println (

--------------------------------------------------------------------------------------------------------------- -----------

Merge two Paths

The technique of merging two paths allows you to define a fixed root directory and then attach the local path, and in nio.2, use the Resolve () method to implement this function.

 // define the fixed path  path base = Paths.get ("c:/rafaelnadal/tournaments/2009"  // resolve BNP.txt file  Path path_1 = base.resolve ("BNP.txt"  // output:c:\rafaelnadal\tournaments\2009\bnp.txt   System.out.println (path_1.tostring ());  // resolve AEGON.txt file  Path path_2 = base.resolve ("AEGON.txt"  // output:c:\rafaelnadal\tournaments\2009\aegon.txt  System.out.println (Path_2.tostring ()); 

There is also a method for the sibling path, calledresolveSibling(),它会根据给定的路径去替换当前的路径。

// define the fixed path Path base = Paths.get ("c:/rafaelnadal/tournaments/2009/bnp.txt"//resolve sibling AEGON.txt File Path Path = base.resolvesibling ("AEGON.txt"//output:c:\rafaelnadal\tournaments\ 2009\aegon.txt System.out.println (path.tostring ());

--------------------------------------------------------------------------------------------------------------- -----------------

Construct a path in two locations

When you need to construct a path from one location to another, you can use therelativize()方法。直接上代码。

Path path01 = Paths.get ("BNP.txt"

In this case, it can be assumed that the two TXT files are in the same level directory, which means you can navigate from one file to another according to the hierarchy of the directory.

// output:  .. \aegon.txt Path path01_to_path02 =//output:  . \bnp.txt Path path02_to_path01 = path02.relativize (path01); System.out.println (PATH02_TO_PATH01);

Another scenario is that two files are not in the same level of the directory, consider the following scenario:

Path path01 = Paths.get ("/tournaments/2009/bnp.txt"= Paths.get ("/tournaments/2011");

Both of these paths have a common root element:/tournaments, 从path01 导航到 path02,你需要向上两个目录层级然后再向下一个层级(..\..\2011)。从path02导航到path01,你需要向上一个层级然后向下两个层级,relativize()方法就是这样做的。

// output:  .. \.. \2011 Path path01_to_path02 =//output:  . \2009\bnp.txt Path path02_to_path01 = path02.relativize (path01); System.out.println (PATH02_TO_PATH01);

Note that if only one path contains the root element, then the relative path is not constructed, and it is guaranteed that two path contains the root element. Even so, the construction of relative paths is dependent on the system.

--------------------------------------------------------------------------------------------------------------- --------------------

Comparison of two paths

The two paths are equal and can be tested in different ways and for a purpose. You can usePath.equals()方法,这个方法并不直接访问文件系统,所以没有强制要求文件必须存在,

Also does not check whether two files are the same file. In some systems, the comparison of paths ignores case, while others are case-sensitive. The same file is represented in the following code, but is not equal.

Path path01 = Paths.get ("/rafaelnadal/tournaments/2009/bnp.txt"= Paths.get ("c:/rafaelnadal/tournaments/ 2009/bnp.txt "if(Path01.equals (path02)) {     System.out.println (" The Paths is equal! "  Else  {     System.out.println (///true }

Sometimes you want to check if two paths are the same directory and file that you can easily usejava.nio.File.Files.isSameFile()方法,要注意,要保证路径是真实存在。

Try {     boolean check = files.issamefile (path01, path02);      if (check) {         System.out.println (//true     else  {         System.out.println ("The paths does not locate the same file!" );      Catch (IOException e) {     System.out.println (e.getmessage ());}

Because path implements theComparable接口,所以你可以使用 compareTo()方法对路径进行比较,根据字典顺序进行比较。

// output:24 int Compare =

You can also perform a local path comparison.

boolean sw = Path01.startswith ("/rafaelnadal/tournaments"); boolean ew = Path01.endswith ("BNP.txt"); SYSTEM.OUT.PRINTLN (SW);   // output:  trueSystem.out.println (EW);  // Output:  

--------------------------------------------------------------------------------------------------------------- ---------------

Traverse the name of a path element

Because path implements theIterable接口,所以你可以得到一个对象然后新型循环遍历一个路径的信息。请看下面的代码。

Path PATH = Paths.get ("C:", "rafaelnadal/tournaments/2009", "BNP.txt" for (path Name:path) {     SYSTEM.OUT.PRINTLN (name); }

The output structure is as follows:

  rafaelnadal

  tournaments

  2009

  BNP.txt

--------------------------------------------------------------------------------------------------------------- --------------

Finish.

  

Use of nio.2 in Java 7-the use of the first section of 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.