Get file in relative path of runnable jar

2

I have been trying for hours to read a file that is in the same directory as the executable JAR:

My code is:

Object obj = parser.parse(new FileReader("configuracion.json"));

But I already tried with

  • "./ configuracion.json"
  • ". \\ configuracion.json"
  • I tried putting it in a "resources" folder in the root of the project and doing the ...getResource("configuracion.json").getPath() but it also did not work when exporting, only during the debug in Eclipse.
  • When I run it in Eclipse (the configuration.json is in the root of the project) it works, but when I export it to a Runnable JAR it throws FileNotFoundException .

    If someone could give a hand I would appreciate it very much.

        
    asked by Genarito 04.01.2018 в 18:07
    source

    1 answer

    2

    To avoid this type of situation, I have a function that searches the directory and checks if the path to return is correct. Edited taking into account the comments

     /**
     * Obtenemos la ruta hasta el fichero , habitualmente situado junto al
     * archivo JAR. En caso contrario, estariamos ejecutando desde un IDE y
     * buscaremos el archivo junto al pom.xml y las carpetas target y src.
     *
     * @param filename nombre fle fichero(con extension) a abrir
     * @return Ruta completa hasta el fichero
     * @throws URISyntaxException
     * @throws IOException
     */
    public static String getRutaRecurso(String filename) throws URISyntaxException, IOException {
        final ProtectionDomain domain;
        final CodeSource source;
        final URL url;
        final URI uri;
        String DirectoryPath;
        String separador_directorios=System.getProperty("file.separator");
        String JarURL;
        File auxiliar;
        domain = Fichero.class.getProtectionDomain();
        source = domain.getCodeSource();
        url = source.getLocation();
        uri = url.toURI();
        JarURL = uri.getPath();
        auxiliar = new File(JarURL);
        //Si es un directorio es que estamos ejecutando desde el IDE. En este caso
        // habrá que buscar el fichero en la carperta  abuela(junto a las carpetas "src" y "target·
        if (auxiliar.isDirectory()) {
            auxiliar = new File(auxiliar.getParentFile().getParentFile().getPath());
            DirectoryPath = auxiliar.getCanonicalPath() + separador_directorios;
        } else {
            JarURL=auxiliar.getCanonicalPath();
            DirectoryPath = JarURL.substring(0, JarURL.lastIndexOf(separador_directorios) + 1);
    
        }
    
        System.out.println(DirectoryPath + filename);
        return DirectoryPath + filename;
    }
    

    In your specific code, it would be adding this in the following way and having the file next to the jar

    Object obj = parser.parse(new FileReader(getRutaRecurso("configuracion.json")));
    

    Take a look to see if it works for you

        
    answered by 04.01.2018 / 18:41
    source