350

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.

mat_boy
  • 12,998
  • 22
  • 72
  • 116

4 Answers4

571

You can just use the Paths class:

Path path = Paths.get(textPath);

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
24

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)

bummi
  • 27,123
  • 14
  • 62
  • 101
  • 10
    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"` – mat_boy Sep 12 '13 at 07:20
  • 1
    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). – Mr.Q Feb 18 '18 at 10:06
19

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"
Cwt
  • 8,206
  • 3
  • 32
  • 27
15

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

Jan Molak
  • 4,426
  • 2
  • 36
  • 32
Arcones
  • 3,954
  • 4
  • 26
  • 46