Create a Path from String in Java7
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");
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"
You can just use the Paths
class:
Path path = Paths.get(textPath);
... assuming you want to use the default file system, of course.