You can just use the Paths class:
Path path = Paths.get(textPath);
... assuming you want to use the default file system, of course.
Answer from Jon Skeet on Stack OverflowYou 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)
Videos
Use:
Paths.get(...).normalize().toString()
Another solution woul be:
Paths.get(...).toAbsolutePath().toString()
However, you get strange results: Paths.get("/tmp", "foo").toString() returns /tmp/foo here. What is your filesystem?
To complete the the fge's answer, I would add some info:
normalize()simply removes redundant pieces of strings in your path, like.or..; it does not operate at the OS level or gives you an absolute path from a relative pathtoAbsolutePath()on the contrary gives you what the name says, the absolute path of thePathobject. But...toRealPath()resolves also soft and hard links (yes they exists also on Windows, so win user, you're not immune). So it gives to you, as the name says, the real path.
So what's the best? It depends, but personally I use toRealPath() the 99% of the cases.
As pointed out by Roberto Bonvallet, since toRealPath() throws an exception if the file does not already exist because, for example, you want to create it. In this case I prefer toAbsolutePath().
Source: Official javadoc