Absolute and Relative Paths – Java I/O: Part II

Absolute and Relative Paths

Directory entries can be referenced using both absolute and relative paths, but the path naming must follow the conventions of the host platform.

An absolute path starts with the platform-dependent root component of the file system, as in the examples above. All information is contained in an absolute path to reference the directory entry—that is, an absolute path uniquely identifies a directory entry in the file system.

A relative path is without designation of the root component and therefore requires additional path information to locate its directory entry in the file system. Typically, a relative path is interpreted in relation to the current directory (see the next subsection). Some examples of relative paths are given below, but they alone are not enough to uniquely identify a directory entry.

Click here to view code image

c/d                on Unix-based platforms
c\d                on Windows-based platforms

Note that in a path, the name elements are all parent directory names, except for the last name element, which can be either a file name or a directory name. The name of a directory entry does not distinguish whether it is a file or a directory in the file system. Although file extensions can be used in a file name for readability, it is immaterial for the file system. Care must also be exercised when choosing name elements, as characters allowed are usually platform dependent.

Java programs should not rely on system-specific path conventions. In the next section we will construct paths in a platform-independent way.

Current and Parent Directory Designators

A file system has a notion of a current directory which changes while traversing in the file system. The current directory is designated by the period character (.) and its parent directory by two periods (..). These designators can be used in constructing paths. Given that the current directory is /a/b in the directory tree shown earlier, Table 21.1 illustrates relative paths constructed using the current and the parent directory designators, and their corresponding absolute paths.

Table 21.1 Using Current and Parent Directory Designators

Relative path (Current directory: /a/b)Absolute path
./c/d/a/b/c/d
./a/b
./../a
./../../ (i.e., the root component)

Leave a Reply

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