373

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.

0

4 Answers 4

597

You can just use the Paths class:

Path path = Paths.get(textPath);

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

Sign up to request clarification or add additional context in comments.

7 Comments

Is there a way for this to work with relative path and full path? i.e giving a path relative to where the project or exe is?
@kuhaku: I think you should ask a new question with details of what you're trying to do and what you've tried.
@JonSkeet is Path.get() is platform independent? meaning that Path.get("lib","p2") will be as lib\p2in Windows and lib/p2 in linux
@KasunSiyambalapitiya: Yes, it should be fine like that.
@JonSkeet Paths.get("/opt/path/"); Its returns as "\opt\path\". Can you please provide the solution.
|
28

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)

2 Comments

I suggest to use File.separarator instead of taking care of the current OS. E.g. "/tmp/foo" is File.separator+"tmp"+File.separator+"foo"
I guess it does not create the actual file, but it creates a Path object. You can use the path object to create the actual file on disk, using Files.createFile(logfilePath).
20

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"

3 Comments

is this platform independant?
I am fairly sure that yes, it is.
Doesn't help when the path comes from an environment variable.
16

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");

1 Comment

@mat_boy yeah but it's no big deal, really. The method already existed in Java 7, except it was previously called Paths.get.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.