How to use Java Path class?

In this tutorial we are discussing Path class of java.nio.file package.

How to use Java Path class?

In this tutorial we are discussing Path class of java.nio.file package.

How to use Java Path class?

java.nio.file.Path Class -  How to use Java Path class?

In this tutorial we are exploring java.nio.file.Path class and learn to use this class in programming. This class is available in Java with Java 7. This class was added in Java as a part of Java NIO2 update in JDK 7. This class is placed in the java.nio.file package and to use it you can use the fully qualified name java.nio.file.Path in your code. This class provides powerful functionality and if you are planning to use I/O functionality of Java then learn this Path class.

The java.nio.file.Path class is used to programmatically represent a path in the OS file system. For example you can completely represent the path of directory under with a file resides along with the file name in the path. If your file resides in c:/examples/java/test1.java then you can present it in a Path object by passing complete path "c:/examples/java/test1.java". This class works even if the provided directory does not exists in the system. If you create instance of Path class it wont create file or directory. To create actual file or directory you have to use the  Files.createFile(Path filePath) method.

  • The object of Path class only represents the file system path. The path given while create Path object may not exist in the system.
  • If you create the instance of Path class by providing some path then it won't actually create or check the underlying file system.
  • To create path into system you can use Files.createFile(Path filePath) method.

This is used to perform various operations to get details in various format from the Path object. For example you can just get the file name using  getFileName() method.

The Path represents a path in the file os file system and it consists of directory path and file name. The Path is system dependent, i.e. path of file system of one Operating System is different from the file system of another Operating System.

This is not platform independent and for windows its uses following format:

c:\user\abc.txt

and under Unix/Linux variant operating system following format is used:

/user/abc.txt

You can use the object of Path class to get extract pieces of information required during development of applications. For example you can get file name, complete path, compare it etc..

How to create Path

There are various ways to create a Path object these are as follows :

Path path = Paths.get("/user/abc.txt");
Path path1 = Paths.get(args[0]);
Path path2 = FileSystems.getDefault().getPath("/user/abc.txt");
Path path3 = Paths.get(System.getProperty("user.home"), "text", "abc.txt");

How to Get the Path Information

Name elements of Path are stored in a sequence i.e. the top level element of directory structure is situated at the index 0 (zero) and the lowest level element of directory structure is situated at the index (n-1), 'n' is the number of name elements. There are various of methods are available in Path which are used to get the information of the existing file. These are as follows :

Method Name Description
getFileName() This method is used to get the name of file or directory of the current path.
Syntax : Path getFileName()
getName(int index) This method is used to get the name of the specified index.
Syntax : Path getName(int index)
getNameCount() This method is used to get the number of element in the specified path.
Syntax : int getNameCount()
getParent() This method is used to get the parent directory.
Syntax : Path getParent()
getRoot() This method is used to get the root of the directory.
Syntax : Path getRoot()

Except these above methods there are some more useful methods in Path.

Method Name Description
endsWith(Path other) This method  tests whether the current path is ends with the specified path or not.
Syntax : boolean endsWith(Path other)
endsWith(String other) This method tests whether the current path is ends with the specified path made up with the specified string path name or not.
Syntax :boolean endsWith(String other)
equals(Object other) This method compares the current path with the given object that whether they are equal or not.
Syntax : boolean equals(Object other)
isAbsolute() This method specifies that whether the current path is absolute or not.
Syntax : boolean isAbsolute()
iterator() This method gives an iterator to iterate over the name element of the current path.
Syntax : Iterator iterator()
resolve(Path other) This method is used to join the current path with given path.
Syntax : Path resolve(Path other)
resolve(String other) This method converted the specified string to a path and then joins this path with the current path.
Syntax : Path resolve(String other)
startsWith(Path other) This method tests whether the current path is started with the specified path or not.
Syntax : boolean startsWith(Path other)
startsWith(String other) This method tests whether the current path is started with the specified path made up with the specified string path or not.
Syntax : boolean startsWith(String other)
subpath(int beginIndex, int endIndex) This method is used to get the relative path from the current path, the returned path is the subsequence of the current path returned from the specified index.
Syntax : Path subpath(int beginIndex, int endIndex)
toString() This method is used to get the path as a String.
Syntax : String toString()
toFile() This method is used to get the File object from the current path.
Syntax : File toFile()

Examples of java.nio.file.Path class

Now we will see few example of java.nio.file.Path class. Following is example of creating the Path and extracting various information from it.

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.LinkOption;

/*
	Web: http://www.roseindia.net
*/

public class NIOPathExample 
{
	public static void main(String[] args) 
	{
		try{
		//Create path
		Path path = Paths.get("c:/examples/java/test1.java");
		
		//Print path
		System.out.println(path.toString());

		//Print File name
		System.out.println(path.getFileName());
		
		//Print Name Count
		System.out.println(path.getNameCount());

		//Another way to getting File Name
		System.out.println(path.getName(path.getNameCount()-1));

		//Print file Realpath
		Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
		System.out.println(realPath);

		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
}

So, you can use Path class for getting details from the it.

Above example can be written using the Java 11 Local-Variable Syntax (var):

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.LinkOption;

/*
	Web: http://www.roseindia.net
*/

public class NIOPathExampleJava11 
{
	public static void main(String[] args) 
	{
		try{
		//Create path
		var path = Paths.get("c:/examples/java/test1.java");
		
		//Print path
		System.out.println(path.toString());

		//Print File name
		System.out.println(path.getFileName());
		
		//Print Name Count
		System.out.println(path.getNameCount());

		//Another way to getting File Name
		System.out.println(path.getName(path.getNameCount()-1));

		//Print file Realpath
		Path realPath = path.toRealPath(LinkOption.NOFOLLOW_LINKS);
		System.out.println(realPath);

		}catch(Exception e){
			System.out.println(e.getMessage());
		}
	}
}

In this section we have learned to use Path class in Java 11. Here are more tutorials of Java: