Preface
The Path class includes various methods that can be used to obtain information about the path, access elements of the path, convert the path to other forms, or extract portions of a path. There are also methods for matching the path string and methods for removing redundancies in a path. This lesson addresses these Pathmethods, sometimes called syntactic operations, because they operate on the path itself and don't access the file system.
This section covers the following:
Creating a Path
A Path instance contains the information used to specify the location of a file or directory. At the time it is defined, a Path is provided with a series of one or more names. A root element or a file name might be included, but neither are required. A Path might consist of just a single directory or file name.
You can easily create a Path object by using one of the following get methods from the Paths (note the plural) helper class:
- Path p1 = Paths.get("/tmp/foo");
- Path p2 = Paths.get(args[0]);
- Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
- Path p4 = FileSystems.getDefault().getPath("/users/sally");
- Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
You can think of the Path as storing these name elements as a sequence. The highest element in the directory structure would be located at index 0. The lowest element in the directory structure would be located at index [n-1], where n is the number of name elements in the Path. Methods are available for retrieving individual elements or a subsequence of the Path using these indexes.
The examples in this lesson use the following directory structure.
Sample Directory Structure
The following code snippet defines a Path instance and then invokes several methods to obtain information about the path: (Below is written in groovy code)
- #!/root/groovy/bin/groovy
- import java.nio.file.Path
- import java.nio.file.Paths
- def os = System.getProperty("os.name").toLowerCase()
- printf("OS=%s\n", os)
- Path path=null
- if('win' in os)
- {
- // Microsoft Windows syntax
- path = Paths.get("C:\\home\\joe\\foo");
- }
- else if('solar' in os)
- {
- // Solaris syntax
- path = Paths.get("/home/joe/foo");
- }
- else
- {
- // Linux like
- path = Paths.get("/home/joe/foo");
- }
- System.out.format("toString: %s%n", path.toString());
- System.out.format("getFileName: %s%n", path.getFileName());
- System.out.format("getName(0): %s%n", path.getName(0));
- System.out.format("getNameCount: %d%n", path.getNameCount());
- System.out.format("subpath(0,2): %s%n", path.subpath(0,2));
- System.out.format("getParent: %s%n", path.getParent());
- System.out.format("getRoot: %s%n", path.getRoot());
The previous example shows the output for an absolute path. In the following example, a relative path is specified:
- if('win' in os)
- {
- // Microsoft Windows syntax
- path = Paths.get("sally\\bar");
- }
- else if('solar' in os)
- {
- // Solaris syntax
- path = Paths.get("sally/bar");
- }
- else
- {
- // Linux like
- path = Paths.get("sally/bar");
- }
Removing Redundancies From a Path
Many file systems use "." notation to denote the current directory and ".." to denote the parent directory. You might have a situation where a Path contains redundant directory information. Perhaps a server is configured to save its log files in the "/dir/logs/." directory, and you want to delete the trailing "/." notation from the path. The following examples both include redundancies:
The normalize method removes any redundant elements, which includes any "." or "directory/.." occurrences. Both of the preceding examples normalize to/home/joe/foo. It is important to note that normalize doesn't check at the file system when it cleans up a path. It is a purely syntactic operation. In the second example, if sally were a symbolic link, removing sally/.. might result in a Path that no longer locates the intended file.
To clean up a path while ensuring that the result locates the correct file, you can use the toRealPath method.
Converting a Path
You can use three methods to convert the Path. If you need to convert the path to a string that can be opened from a browser, you can use toUri. For example:
- Path p1 = Paths.get("/home/logfile");
- // Result is file:///home/logfile
- System.out.format("%s%n", p1.toUri());
- public class FileTest {
- public static void main(String[] args) {
- if (args.length < 1) {
- System.out.println("usage: FileTest file");
- System.exit(-1);
- }
- // Converts the input string to a Path object.
- Path inputPath = Paths.get(args[0]);
- // Converts the input Path
- // to an absolute path.
- // Generally, this means prepending
- // the current working
- // directory. If this example
- // were called like this:
- // java FileTest foo
- // the getRoot and getParent methods
- // would return null
- // on the original "inputPath"
- // instance. Invoking getRoot and
- // getParent on the "fullPath"
- // instance returns expected values.
- Path fullPath = inputPath.toAbsolutePath();
- }
- }
This method throws an exception if the file does not exist or cannot be accessed. For example:
- try {
- Path fp = path.toRealPath();
- } catch (NoSuchFileException x) {
- System.err.format("%s: no such" + " file or directory%n", path);
- // Logic for case when file doesn't exist.
- } catch (IOException x) {
- System.err.format("%s%n", x);
- // Logic for other sort of file error.
- }
You can combine paths by using the resolve method. You pass in a partial path , which is a path that does not include a root element, and that partial path is appended to the original path. For example, consider the following code snippet:
- // Solaris
- Path p1 = Paths.get("/home/joe/foo");
- // Result is /home/joe/foo/bar
- System.out.format("%s%n", p1.resolve("bar"));
- // Microsoft Windows
- Path p1 = Paths.get("C:\\home\\joe\\foo");
- // Result is C:\home\joe\foo\bar
- System.out.format("%s%n", p1.resolve("bar"));
- // Result is /home/joe
- Paths.get("foo").resolve("/home/joe");
A common requirement when you are writing file I/O code is the capability to construct a path from one location in the file system to another location. You can meet this using the relativize method. This method constructs a path originating from the original path and ending at the location specified by the passed-in path. The new path is relative to the original path.
For example, consider two relative paths defined as joe and sally:
- Path p1 = Paths.get("joe");
- Path p2 = Paths.get("sally");
- // Result is ../sally
- Path p1_to_p2 = p1.relativize(p2);
- // Result is ../joe
- Path p2_to_p1 = p2.relativize(p1);
- Path p1 = Paths.get("home");
- Path p3 = Paths.get("home/sally/bar");
- // Result is sally/bar
- Path p1_to_p3 = p1.relativize(p3);
- // Result is ../..
- Path p3_to_p1 = p3.relativize(p1);
Comparing Two Paths
The Path class supports equals, enabling you to test two paths for equality. The startsWith and endsWith methods enable you to test whether a path begins or ends with a particular string. These methods are easy to use. For example:
- Path path = ...;
- Path otherPath = ...;
- Path beginning = Paths.get("/home");
- Path ending = Paths.get("foo");
- if (path.equals(otherPath)) {
- // equality logic here
- } else if (path.startsWith(beginning)) {
- // path begins with "/home"
- } else if (path.endsWith(ending)) {
- // path ends with "foo"
- }
- Path path = ...;
- for (Path name: path) {
- System.out.println(name);
- }
You can also put Path objects into a Collection. See the Collections trail for more information about this powerful feature.
When you want to verify that two Path objects locate the same file, you can use the isSameFile method, as described in Checking Whether Two Paths Locate the Same File.
Supplement
* Java 獲取當前操作系統的信息
連結錯誤?
回覆刪除Java 獲取當前操作系統的信息
localhost/jforum/posts/list/2266.page
Thanks for the reminding, the link has been updated:
刪除http://puremonkey2010.blogspot.com/2012/09/java-java.html