Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 1000
mat_boy Avatar asked Jun 04 '13 13:06

mat_boy


People also ask

How do you turn a string into a path?

To convert a string to path, we can use the built-in java. nio. file. Paths class get() static method in Java.

How do I create a path object?

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.

Is a path a string?

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.


2 Answers

You can just use the Paths class:

Path path = Paths.get(textPath); 

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

like image 114
Jon Skeet Avatar answered Oct 04 '22 11:10

Jon Skeet


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)

like image 39
Karthik Karuppannan Avatar answered Oct 04 '22 13:10

Karthik Karuppannan