Create a Path from String in Java7

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.


You can just use the Paths class:

Path path = Paths.get(textPath);

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


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)


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"