The path to read this file in Java is correct


The path I put in the FileReader to read the file would be correct, since it does not stop going to the FileNotFoundException with the method in the logical package and the document in Files all within the src.

BufferedReader fichero = new BufferedReader(new FileReader("Files/clientes.dat"));
            while (fichero.ready()) {
                linea = fichero.readLine();
                String[] trozos = linea.split("@");
                if(trozos[0] == usuarioCliente) {   //El Cliente ya esta Registrado
                    return true;

Greetings and thank you very much.

asked by AGOI 30.12.2018 в 23:02

1 answer


The problem that is presented here is that it is trying to read a file from the folder where the Java Application is executed. and not The resource (everything that is in the src folder, are resources that will be packaged inside a .Jar) and in the case of using an IDE the folder of execution is relative to where the .class is compiled, therefore:

based on the answer to this question: execute .exe from within .jar in java

we must read the resource for it, the Class is used java.lang.Class and its method getResourceAsStream() to get a InputStream

 /*NOTA: /Files/clientes.dat es el folder relativo a la raiz (src folder)
 NOTA#2: en mi caso utilizo NewMain que es el nombre de la clase que utilize como prueba,
 pero en tu caso debe tener el nombre de la clase donde se esta leyendo.
 o "this.getClass().getResourceAsStream()"
 InputStream resourceStream = NewMain.class.getResourceAsStream("/Files/clientes.dat");

now to use it in a BufferedReader a Wrap is simply done:

//donde "UTF-8" es el Character set. puede utilizarse otro o el que sea requerido por el archivo. 
BufferedReader br = new BufferedReader(new InputStreamReader(resourceStream, "UTF-8"));
answered by 02.01.2019 / 20:02