Cómo obtener el contenido de una carpeta y ponerlo en una ArrayList


Quiero usar

File f = new File("C:\\");

Para hacer una ArrayList con el contenido de la carpeta.

No soy muy bueno con los lectores en búfer, así que por favor dime si eso es mejor.

Aquí está el código que tengo hasta ahora:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;


public class buffered_read {
public static void main(String[] args) {
    File f = new File("C:\\");
    int x = 0;
    boolean b = true;
    File list[];
    while(b = true){

    }
}
}

Gracias, obiedog

 29
Author: James Dunn, 2011-09-04

5 answers

La forma más fácil de hacerlo es:

File f = new File("C:\\");
ArrayList<File> files = new ArrayList<File>(Arrays.asList(f.listFiles()));

Y si lo que quieres es una lista de nombres:

File f = new File("C:\\");
ArrayList<String> names = new ArrayList<String>(Arrays.asList(f.list()));
 62
Author: user927911,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-04 20:06:27

¿Ha leído la documentación de la API para java.io.File?

File f = new File("C:\\");
File[] list = f.listFiles();
 24
Author: Philipp Reichart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-04 20:00:30

El File-class ofrece un listFiles()-método que devuelve un File-array de todos los archivos de la carpeta actual.

Para hacer una ArrayList de ellos, puede utilizar el Arrays-clase y es asList()-método . Véase aquí .

Si solo necesita los nombres de archivo o rutas como Cadenas, también hay una list()-método que devuelve un arreglo de cadena. Para convertir la matriz en una ArrayList, siga los pasos ilustrados en la pregunta vinculada.

 4
Author: Lukas Knuth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:14

Las transmisiones son rápidas y muy fáciles de leer:

final Path rootPath = Paths.get("/tmp");

// All entries Path objects
ArrayList<Path> all = Files
        .list(rootPath)
        .collect(Collectors.toCollection(ArrayList::new));

// Only regular files at Path objects
ArrayList<Path> regularFilePaths = Files
        .list(rootPath)
        .filter(Files::isRegularFile)
        .collect(Collectors.toCollection(ArrayList::new));

// Only regular files as String paths
ArrayList<String> regularPathsAsString = Files
        .list(rootPath)
        .filter(Files::isRegularFile)
        .map(Path::toString)
        .collect(Collectors.toCollection(ArrayList::new));
 1
Author: Kamran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-27 16:03:31

Si desea recuperar todos los archivos recursivamente, puede hacer algo como a continuación

public class FileLister {

    static List<String> fileList = new ArrayList<String>();

    public static void main(String[] args) {
        File file = new File("C:\\tmp");
        listDirectory(file);
        System.out.println(fileList);
    }

    public static void listDirectory(File file) {
        if(file.isDirectory()) {
            File[] files = file.listFiles();
            for(File currFile : files) {
                listDirectory(currFile);
            }
        }
        else {
            fileList.add(file.getPath());
        }
    }
}
 0
Author: Vishal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-25 03:44:18