Cómo obtener la ruta absoluta al archivo en la carpeta / resources en su proyecto
Asume la configuración estándar de maven.
Digamos que en tu carpeta de recursos tienes un archivo abc
.
En Java, ¿cómo puedo obtener la ruta absoluta al archivo, por favor?
5 answers
Puede crear un objeto File
y usar el método getAbsolutePath
:
File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();
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-27 18:56:42
La manera apropiada que realmente funciona:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
Ahora no importa dónde está físicamente el archivo en el classpath, se encontrará siempre y cuando el recurso sea realmente un archivo y no una entrada JAR.
(¡Lo aparentemente obvio new File(resource.getPath())
no funciona para todos los caminos! ¡La ruta sigue codificada en URL!)
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
2014-02-05 23:56:17
Debe especificar la ruta iniciada desde /
URL resource = YourClass.class.getResource("/abc");
Paths.get(resource.toURI()).toFile();
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
2017-12-12 17:17:03
Cree la instancia de ClassLoader de la clase que necesita, luego puede acceder a los archivos o recursos fácilmente.
ahora accede a path usando el método getPath()
de esa clase.
ClassLoader classLoader = getClass().getClassLoader();
String path = classLoader.getResource("chromedriver.exe").getPath();
System.out.println(path);
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
2018-01-05 12:02:25
Para devolver un archivo o ruta de archivo
URL resource = YourClass.class.getResource("abc");
File file = Paths.get(resource.toURI()).toFile(); // return a file
String filepath = Paths.get(resource.toURI()).toFile().getAbsolutePath(); // return file path
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
2018-06-25 18:13:35