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
.
To convert a string to path, we can use the built-in java. nio. file. Paths class get() static method in Java.
You can easily create a Path object by using one of the following get methods from the Paths (note the plural) helper class: Path p1 = Paths. get("/tmp/foo"); Path p2 = Paths. get(args[0]); Path p3 = Paths.
A path is a string that provides the location of a file or directory. A path does not necessarily point to a location on disk; for example, a path might map to a location in memory or on a device.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With