Create a Path from String in Java7

StringPathNioJava 7

String Problem Overview


How can I create a java.nio.file.Path object from a String object in Java 7?

I.e.

String textPath = "c:/dir1/dir2/dir3";
Path path = ?;

where ? is the missing code that uses textPath.

String Solutions


Solution 1 - String

You can just use the Paths class:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

Solution 2 - String

From the javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Path p1 = Paths.get("/tmp/foo"); 

is the same as

Path p4 = FileSystems.getDefault().getPath("/tmp/foo");

Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));

Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log"); 

In Windows, creates file C:\joe\logs\foo.log (assuming user home as C:\joe)
In Unix, creates file /u/joe/logs/foo.log (assuming user home as /u/joe)

Solution 3 - String

If possible I would suggest creating the Path directly from the path elements:

Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"

Solution 4 - String

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmat_boyView Question on Stackoverflow
Solution 1 - StringJon SkeetView Answer on Stackoverflow
Solution 2 - StringKarthik KaruppannanView Answer on Stackoverflow
Solution 3 - StringsevenforceView Answer on Stackoverflow
Solution 4 - StringArconesView Answer on Stackoverflow