Crear una ruta a partir de una cadena en Java7


¿Cómo puedo crear un java.nio.file.Path objeto de un objeto String en Java 7?

Es decir,

String textPath = "c:/dir1/dir2/dir3";
Path path = ?;

Donde ? es el código que falta que usa textPath.

Author: mat_boy, 2013-06-04

3 answers

Solo puede usar el Paths clase:

Path path = Paths.get(textPath);

... suponiendo que desea utilizar el sistema de archivos por defecto, por supuesto.

 316
Author: Jon Skeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-04 13:45:22

De los javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

Path p1 = Paths.get("/tmp/foo"); 

Es lo mismo que

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

En Windows, crea el archivo C:\joe\logs\foo.log (asumiendo el inicio del usuario como C:\joe)
En Unix, crea el archivo /u/joe/logs/foo.log (asumiendo el inicio del usuario como /u/joe)

 14
Author: Karthik Karuppannan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-11 22:15:30

Si es posible, sugeriría crear el Path directamente desde los elementos path:

Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"
 5
Author: sevenforce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-27 15:26:14