Encontrar un archivo específico en una carpeta en Java

I need to find a specific file for example, info.txt in a folder. The problem is I do not know under what level the file is. For example, the file can be in a sub-folder or in a sub-folder of a sub-folder.

So this means I have to go through recursion.... Or there is a simple way to complete this task. I am using JDK 1.5.

preguntado el 10 de septiembre de 13 a las 00:09

Recursion is the way to go, but consider this: do you return the first occurrence of info.txt you find? -

Yes, I shall return the first occurrence of info.txt -

3 Respuestas

Puedes usar apache commons-io FileUtils. Assuming you want to recursively search for file foo bajo directorio messyfolder:

Collection<File> results = FileUtils.listFiles(new File("messyfolder"), 
                                               new NameFileFilter("foo"), 

Respondido el 10 de Septiembre de 13 a las 02:09

You dont have to use recursion, but its a good idea. You can use the File object in java to help you along. A couple of the key things you will be using:

  • al isDirectory() function. Fairly self explanatory.
  • Si File object is a directory, you will have to use the listFiles() function. Returns an array of file objects which are files AND directories. You just call your recursive function on this array.
  • También puede interesarle Nombre de archivoFiltro interface to help you along.

A simple mock up of the code would be something like

File findFile(String fileName, File[] files){
    for(File file : files){
        if(file.isDirectory) File f = findFile(fileName, file.listFiles());
        if(f!=null) return f;
        if(file.getName.equals(fileName)) return file;
    return null;

Respondido el 10 de Septiembre de 13 a las 02:09

IIRC java 7 had some directory walking utils. You can also use a stack or a queue to walk a directory tree without recursion.

Respondido el 10 de Septiembre de 13 a las 01:09

some more details in your answer would be helpful - Caos

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.