In Java, we can convert a String representation of a file or directory path into a path object using the Paths utility class. It is a part of the java.nio.file package. The Paths class provides a method called get(String file path location) that converts a sequence of strings representing a path into a Path object.
In this article, we will learn How to Convert a String to a Path in Java.
Import these classes:
import java.nio.file.Paths;
import java.nio.file.Path;
Program to Convert a String to a Path in Java
We can use the Paths.get() method to convert the string to a path.
// Java Program to Convert a String
// To a Path Using Paths.get() method
import java.nio.file.Path;
import java.nio.file.Paths;
// Driver Class
class GFG {
// Main Function
public static void main(String args[])
{
// Define the String representing the File Path
String location = "C:/Users/Desktop/New Folder";
// Convert the string to a Path object
Path path = Paths.get(location);
// Output the path
System.out.println(path);
}
}
Output
C:/Users/Desktop/New Folder
Explanation of the Program:
- We define a
Stringvariablelocationcontaining the file path. - Then we have used the static
Paths.get()method to convert thelocationstring into aPathobject. - This method returns a
Pathobject constructed from one or more strings that when joined form a path string.
If we do not have the entire path in string, we can provide it piece by piece, or folder by folder. By using the Paths.get() method and pass each folder as a separate parameter.
import java.nio.file.Path;
import java.nio.file.Paths;
// Driver Class
class GFG {
// Main Function
public static void main(String args[])
{
// Creating Path Object Piece by Piece
// Using Paths.get()
Path path = Paths.get("C:", "Users", "Desktop" ,"New Folder");
System.out.println(path);
}
}
Output
C:/Users/Desktop/New Folder
Explanation of the Program:
In the above program,
- We have used the static
Paths.get()method to create aPathobject. Again, this method takes multiple string arguments representing individual elements of the path. - Here, each argument represents a component of the path, such as directory name, file name etc.
- The resulting
Pathobject represents the concatenation of these elements by forming the complete path.