Working with Path Objects – Java I/O: Part II

21.3 Working with Path Objects

The java.nio.file.Path interface provides a myriad of methods to query and manipulate Path objects. In this section, selected methods from the Path interface are presented for working on Path objects. A majority of these methods perform syntactic operations on the path string contained in a Path object. As Path objects are immutable, the methods return a new Path object, making it possible to use this distinctive style of method chaining. There is also no requirement that the path string in a Path object must refer to an existing resource. Very few methods enforce this requirement, and if they do, they will throw a checked IOException if that it is not the case.

Querying Path Objects

The following methods of the java.nio.file.Path interface can be used for querying a Path object for its various properties. The names of most methods reflect their operation. The description in the API of these methods and Example 21.1 below should aid in understanding their functionality.

String toString()

Returns the text representation of this path.

boolean isAbsolute()

Determines whether this path is an absolute path or not.

FileSystem getFileSystem()

Returns the file system that created this object. Each Path object is created with respect to a file system.

Path getFileName()

Returns the name of the directory entry denoted by this path as a Path object— that is, the last name element in this path which denotes either a file or a directory.

Path getParent()

Returns the parent path, or null if this path does not have a parent—that is, logically going up one level in the directory hierarchy from the current position given by this path. It returns null if this Path does not have a parent—for example, if the path denotes the root component or it is a relative path that comprises a single name element, as there is no parent in these cases.

Path getRoot()

Returns the root component of this path as a Path object, or null if this path does not have a root component.

int getNameCount()

Returns the number of name elements in the path. It returns the value n, where n-1 is the index of the last name element and the first name element has index 0. Note that the root component is not included in the count of the name elements.

Path getName(int index)

Returns a name element of this path as a Path object, where the name element closest to the root component has index 0.

Click here to view code image

Path subpath(int beginIndex, int endIndex)

Returns a relative Path that is a subsequence of the name elements of this path, where beginIndex is inclusive but endIndex is exclusive (i.e., name elements in the range [beginIndex, endIndex)). Illegal indices will result in an Illegal-ArgumentException.

Click here to view code image

boolean startsWith(Path other)
default boolean startsWith(String other)

Determine whether this path starts with either the given path or a Path object constructed from the given other string. The methods can be used for conditional handing of paths.

Click here to view code image

boolean endsWith(Path other)
default boolean endsWith(String other)

Determine whether this path ends with either the given path or a Path object constructed from the given other string. These methods can be used for conditional handing of paths.

Example 21.1 illustrates methods for querying a Path object. An absolute path is created at (1). The output from the program shows the result of executing methods for text representation at (2), determining whether a path is absolute at (3), which file system created the path at (4), accessing name elements at (5), and testing the prefix and the suffix of a path at (6).

Example 21.1 Querying Path Objects

Click here to view code image

import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
public class QueryingPaths {
  public static void main(String[] args) {
    FileSystem dfs = FileSystems.getDefault();     // The default file system
    String nameSeparator = dfs.getSeparator();     // The name separator
    Path absPath = Path.of(nameSeparator, “a”, “b”, “c”);                // (1)
    System.out.printf(“toString(): %s%n”,   absPath);                    // (2)
    System.out.printf(“isAbsolute(): %s%n”, absPath.isAbsolute());       // (3)
    System.out.printf(“getFileSystem(): %s%n”,
                       absPath.getFileSystem().getClass().getName());    // (4)
    System.out.println(“\n***Accessing Name Elements:”);                 // (5)
    System.out.printf(“getFileName(): %s%n”,  absPath.getFileName());
    System.out.printf(“getParent(): %s%n”,    absPath.getParent());
    System.out.printf(“getRoot(): %s%n”,      absPath.getRoot());
    System.out.printf(“getNameCount(): %d%n”, absPath.getNameCount());
    List<Path> pl = new ArrayList<>();
    absPath.forEach(p -> pl.add(p));
    System.out.printf(“List of name elements: %s%n”,  pl);
    System.out.printf(“getName(0): %s%n”,     absPath.getName(0));
    System.out.printf(“subpath(0,2): %s%n”,   absPath.subpath(0,2));
    System.out.println(“\n***Path Prefix and Suffix:”);                  // (6)
    System.out.printf(“startsWith(\”%s\”): %s%n”,
                      nameSeparator + “a”,
                      absPath.startsWith(nameSeparator + “a”));
    System.out.printf(“endsWith(\”b/c\”): %s%n”,
                      absPath.endsWith(“b/c”));
  }
}

Possible output from the program:

Click here to view code image

toString(): /a/b/c
isAbsolute(): true
getFileSystem(): sun.nio.fs.MacOSXFileSystem
***Accessing Name Elements:
getFileName(): c
getParent(): /a/b
getRoot(): /
getNameCount(): 3
List of name elements: [a, b, c]
getName(0): a
subpath(0,2): a/b
***Path Prefix and Suffix:
startsWith(“/a”): true
endsWith(“b/c”): true

Categories: , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *