How To Get File Path For Java That Works On Both Windows And Mac

How To Get File Path For Java That Works On Both Windows And Mac 3,8/5 4839 votes

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 Path methods, sometimes called syntactic operations, because they operate on the path itself and don't access the file system.

This section covers the following:

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 Path methods, sometimes called syntactic operations, because they operate on. Goto java.com and click on the Free Java Download button. Click on the Save button and save Java software on the Desktop. Verify that Java software is saved on the Desktop. Open Windows Command Prompt window. Windows XP: Click Start - Run - Type: cmd. Windows Vista and Windows 7: Click Start - Type: cmd in the Start Search field.

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:

The Paths.get method is shorthand for the following code:

The following example creates /u/joe/logs/foo.log assuming your home directory is /u/joe, or C:joelogsfoo.log if you are on Windows.

Retrieving Information about a Path

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:

Here is the output for both Windows and the Solaris OS:

Method InvokedReturns in the Solaris OSReturns in Microsoft WindowsComment
toString/home/joe/fooC:homejoefooReturns the string representation of the Path. If the path was created using Filesystems.getDefault().getPath(String) or Paths.get (the latter is a convenience method for getPath), the method performs minor syntactic cleanup. For example, in a UNIX operating system, it will correct the input string //home/joe/foo to /home/joe/foo.
getFileNamefoofooReturns the file name or the last element of the sequence of name elements.
getName(0)homehomeReturns the path element corresponding to the specified index. The 0th element is the path element closest to the root.
getNameCount33Returns the number of elements in the path.
subpath(0,2)home/joehomejoeReturns the subsequence of the Path (not including a root element) as specified by the beginning and ending indexes.
getParent/home/joehomejoeReturns the path of the parent directory.
getRoot/C:Returns the root of the path.

The previous example shows the output for an absolute path. In the following example, a relative path is specified:

Here is the output for Windows and the Solaris OS:

Method InvokedReturns in the Solaris OSReturns in Microsoft Windows
toStringsally/barsallybar
getFileNamebarbar
getName(0)sallysally
getNameCount22
subpath(0,1)sallysally
getParentsallysally
getRootnullnull

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. This method is described in the next section, Converting a Path.

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:

The toAbsolutePath method converts a path to an absolute path. If the passed-in path is already absolute, it returns the same Path object. The toAbsolutePath method can be very helpful when processing user-entered file names. For example:

The toAbsolutePath method converts the user input and returns a Path that returns useful values when queried. The file does not need to exist for this method to work.

The toRealPath method returns the real path of an existing file. This method performs several operations in one:

  • If true is passed to this method and the file system supports symbolic links, this method resolves any symbolic links in the path.
  • If the Path is relative, it returns an absolute path.
  • If the Path contains any redundant elements, it returns a path with those elements removed.

This method throws an exception if the file does not exist or cannot be accessed. You can catch the exception when you want to handle any of these cases. For example:

Joining Two Paths

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:

Passing an absolute path to the resolve method returns the passed-in path:

Java new file from path

Creating a Path Between Two Paths

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:

In the absence of any other information, it is assumed that joe and sally are siblings, meaning nodes that reside at the same level in the tree structure. To navigate from joe to sally, you would expect to first navigate one level up to the parent node and then down to sally:

Consider a slightly more complicated example:

In this example, the two paths share the same node, home. To navigate from home to bar, you first navigate one level down to sally and then one more level down to bar. Navigating from bar to home requires moving up two levels.

A relative path cannot be constructed if only one of the paths includes a root element. If both paths include a root element, the capability to construct a relative path is system dependent.

The recursive Copy example uses the relativize and resolve methods.

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:

The Path class implements the Iterable interface. The iterator method returns an object that enables you to iterate over the name elements in the path. The first element returned is that closest to the root in the directory tree. The following code snippet iterates over a path, printing each name element: Ramayya vasthavayya movie free download dvdrip.

The Path class also implements the Comparable interface. You can compare Path objects by using compareTo which is useful for sorting.

You can also put Path objects into a Collection. See the Collections trail for more information about this powerful feature.

Send a person a Super-Like Message3. Expand your business opportunities by having your own personal contactbook within the app5. Download imnul stelei tap tap. Exchange business cards by using QR-code4.

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.