I am searching for a file called "myFile.java" contained in a folder where there are more folders, for example:
Here the code that I have made, I had thought of a recursive call (I send as parameter file as directory and the name of the file as String)
private static void buscarArchivo(String fichero, File directorioFile) {
//Primero que todo listo mis ficheros utilizando .listFiles
//este método devuelve todos los ficheros asociados al directorio en un array de Files.
File[] lista = directorioFile.listFiles();
if (lista != null) {
for (File elemento : lista) {
if (elemento.isDirectory()) { //.isDirectory comprueba si el fichero instanciado en una clase File es un directorio o no
//Anteriormente solo comprobamos que si existia el directorio pero no el archivo.
buscarArchivo(fichero, elemento);
} else if (fichero.equalsIgnoreCase(elemento.getName())) {
//buscarArchivo(fichero, elemento);
System.out.println("Archivo encontrado con exito! ");
System.out.println (elemento.getParentFile());
System.out.println(elemento.getName());
System.out.println("\n-----------------------------");
}
}
}
}
When calling the method in the main it only indicates that the route, if it exists, is not executed, what am I doing wrong?
public static void main(String args[]){
String fichero = "MiArchivo.java";
//Lo primero que hay que hacer es crear un objeto de tipo File con el nombre del directorio a listar.
File directorioFile = new File("C:\\Users\\Ruta");
//Comprueblo que el directorio existe con un metodo que se llama .(exist) que hace parte de la clase File de java
if (directorioFile.exists()){
System.out.println("El directorio existe, procediendo a buscar el fichero...");
//Primero listo todos los archivos de la carpeta
buscarArchivo(fichero, directorioFile);
}
else{
System.out.println("El directorio no existe, verifique la ruta...");
}
}
NOTE: When things don't work out, it's important to:
Debug the program and check the execution step by step, that the expected values come out. And when they don't come out, investigate why.
Read the documentation of the methods used.
Solution:
Javadoc for java.io.File#listFiles() ; my emphasis:
listFiles() only returns the files, not the directories. To get it to return everything, you can use java.io.File#list() which returns both files and directories.
If (for example) you had printed the list of elements obtained by listFiles , you would have seen that the directories did not come out and you would have been able to pull the thread.
Actually your method is not that far from working. You are missing three things (detailed below)