In this post, we will see how to convert String to Path in Java.
Using Paths’get() method [ Java 7 ]
To convert String to Path, use jva.nio.file.Paths's get()
method. It is a static method.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.nio.file.Path; import java.nio.file.Paths; public class CreatePathFromStringMain { public static void main(String[] args) { String pathStr = "C:/temp/tempFile.txt"; // Create path from string Path path = Paths.get(pathStr); System.out.println("Path => "+path); } } |
Output:
1 2 3 |
Path => C:\temp\tempFile.txt |
You can also join multiple strings using Paths
‘s get()
method. It will join all the String with delimiter /
.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.arpit.java2blog; import java.nio.file.Path; import java.nio.file.Paths; public class CreatePathFromStringMain { public static void main(String[] args) { // Create path from string Path path = Paths.get("C:","temp","tempFile.txt"); System.out.println("Path => "+path); } } |
Output:
1 2 3 |
Path => C:\temp\tempFile.txt |
Using Path’s of() method [ Java 11 ]
There is new method of()
introduced in Java 11 which takes String as argument and provides the Path object.
Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; import java.nio.file.Path; public class CreatePathFromStringMain { public static void main(String[] args) { String pathStr = "C:/temp/tempFile.txt"; // Create path from string Path path1 = Path.of(pathStr); System.out.println("Path => "+path1); // Using multiple Strings Path path2 = Path.of("C:","temp","tempFile.txt"); System.out.println("Path Using multiple Strings => "+path2); } } |
Output:
1 2 3 4 |
Path => C:\temp\tempFile.txt Path Using multiple Strings => C:\temp\tempFile.txt |
That’s all about how to convert String to Path in Java.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.