Threads when looking for files recursively java

0

I am trying to get the files and folders recursively in an ArrayList using threads, since the program if what I'm looking for has many files and directories remains frozen until it ends and I do not know very well what I have to do, this is the wireless code, working, I hope someone can explain how to do it.

public static void main(String[] args) {

    FilenameFilter textFilter = new FilenameFilter() {
                public boolean accept(File dir, String name) {
                        String lowercaseName = name.toLowerCase();
                        if (lowercaseName.contains("prueba")) {
                                return true;
                        } else {
                                return false;
                        }
                }
    };

    ArrayList<File> archivos = new ArrayList(busqueda(new File(ruta),textFilter,true));
}

public static Collection busqueda(File directorio, FilenameFilter filtro, boolean recursivo) {

    Vector archivos = new Vector();

    File[] entries = directorio.listFiles();

    for (File entry : entries) {
        if (filtro == null || filtro.accept(directorio, entry.getName())) {
            archivos.add(entry);
        }

        if (recursivo && entry.isDirectory()) {
            archivos.addAll(busqueda(entry, filtro, recursivo));
        }
    }

    return archivos;
}
    
asked by Seru 22.02.2018 в 21:01
source

1 answer

0

You just have to call the busqueda(...) method within a thread, as I show you in the example:

    final ArrayList<File> archivos = new ArrayList<>();

    new Thread(new Runnable() {

        @Override
        public void run() {
            archivos.addAll(busqueda(new File(ruta),textFilter,true));
        }
    }).start();

It is important to emphasize that all the variables that you use within the thread, if you implement it in this way, must be declared as final . To avoid this, you can use some implementation variants such as Create a class that implements the Runnable interface and pass the parameters of the method to the constructor of that class. Something like this:

class MyRunnable implements Runnable {

    private List<File> target;
    private File ruta;
    private FilenameFilter filter;
    private boolean recursivo;

    public MyRunnable(List<File> target, File ruta, FilenameFilter filter, boolean recursivo) {
        super();
        this.target = target;
        this.ruta = ruta;
        this.filter = filter;
        this.recursivo = recursivo;
    }

    @Override
    public void run() {
        target.addAll(busqueda(ruta, filter, true));
    }
}

then you use it like this: new Thread(new MyRunnable(archivos, new File(ruta), textFilter, true)).start();

Of course, the busqueda(...) method must be accessible by the MyRunnable class.

    
answered by 22.02.2018 / 21:28
source