Create a Path from String in Java7


Translate

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.


所有的回答
  • Translate

    You can just use the Paths class:

    Path path = Paths.get(textPath);
    

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


  • Translate

    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)


  • Translate

    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"
    

  • Translate

    Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is an 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");