I am performing a recursive method that searches for a file called "myFile.java" contained in a folder where there are more folders.
private static void buscarArchivo(String fichero, File directorioFile, int pos) throws IOException {
//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) {//Por si no hay archivos en la ruta uno nunca sabe
if(pos < lista.length){//Recorro mi lista de "Files" algunos son directorios de carpetas y otros archivos contenidos
//en dichos directorios
File archivoAuxiliar= lista[pos]; //Creo un objeto de tipo File para guardar ahi lo que sera bien un diretorio o archivo
if (archivoAuxiliar.isDirectory()) {//Verifico que sea una ruta o archivo
//System.out.println(archivoAuxiliar.getName());
buscarArchivo(fichero, lista[pos+1],pos);//Si es verdadero llamo el metodo nuevamente enviando la siguiento posicion de la lista
//que vendria siendo otra carpeta con mas carpetas y archivos en esta.
}else{//Si es un archivo los compara hasta encontrar el que buscamos
if(fichero.equals(archivoAuxiliar.getName())==true){
System.out.println("\n-----------------------------");
System.out.println("Archivo encontrado con exito! "+archivoAuxiliar.getName()+"\n En la ruta: "+archivoAuxiliar.getParentFile());
System.out.println("\n-----------------------------");
}
}
}
}else{
System.out.println("Ups.. No hay archivos en la ruta!");
}
}
Perhaps the returns are misplaced or missing returns? I put a couple of Sysos between the iterations of the positions to see if it entered correctly and if it accesses the folder where the file is but it does not return if it found it and where? What am I doing wrong?
Here the main in case you want to help me and use it:
public static void main(String args[]) throws IOException{
String fichero = "MiArchivo.java.txt"; //No eliminar el .txt ya que windows por lo menos en mi caso lo detecta como .txt siendo.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...");
//Cambiar de acuerdo a la ruta que valla a buscar en su pc
//Compruebo que el directorio existe con un metodo que se llama .isDirectory que hace parte de la clase File de java
if (directorioFile.isDirectory()){//.isDirectory comprueba si el fichero instanciado en una clase File es un directorio o no
System.out.println("El directorio existe, procediendo a buscar el fichero...");
System.out.println("\n");
buscarArchivo(fichero, directorioFile,0);
}
else{
System.out.println("El directorio no existe, verifique la ruta...");
}
}
As I told you, the problem you are having is that you are not iterating all the contents of the current directory before performing a recursive search in its sub-directories.
here is the problem
Then you do this by expecting to iterate through the contents of the current directory with a recursive call to the method
These are very buggy since at most you would be doing a deep search through a single branch of the directory structure. But as soon as what it finds is a file, the method will end, being this the one sought or not, even if there are files and directories to consult.
What I would do is: iterate over the entire contents of the directory to find the file. If the parsed element is a file and its name matches the searched one, I return it. If it is a directory then I apply the same search process recursively on it.
It would be something like this:
This method will return an instance of
File
representing the file found, ornull
if the file is not found.Note that even though you iterate through the contents of the current directory, the search process is recursive because the method
buscarArchivo()
calls itself over and over again.