How to Convert a String to a Path in Java?
Last Updated :
19 Feb, 2024
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
import java.nio.file.Path;
import java.nio.file.Paths;
class GFG {
public static void main(String args[])
{
String location = "C:/Users/Desktop/New Folder" ;
Path path = Paths.get(location);
System.out.println(path);
}
}
|
Output
C:/Users/Desktop/New Folder
Explanation of the Program:
- We define a
String
variable location
containing the file path.
- Then we have used the static
Paths.get()
method to convert the location
string into a Path
object.
- This method returns a
Path
object 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.
Java
import java.nio.file.Path;
import java.nio.file.Paths;
class GFG {
public static void main(String args[])
{
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 a Path
object. 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
Path
object represents the concatenation of these elements by forming the complete path.
Share your thoughts in the comments
Please Login to comment...