Encontrar un archivo específico en una carpeta en Java
Frecuentes
Visto 110 veces
0
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.
3 Respuestas
2
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"),
TrueFileFilter.INSTANCE)
Respondido el 10 de Septiembre de 13 a las 02:09
1
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 thelistFiles()
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
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java or haz tu propia pregunta.
Recursion is the way to go, but consider this: do you return the first occurrence of
info.txt
you find? - Sotirios DelimanolisYes, I shall return the first occurrence of info.txt - Exploring