Problem with list directories with java

0

I'm trying to list all the files in the C: \ directory of my PC. Smaller directories with 11,000 files are picking up normally, it takes a while, but it's no problem. The problem is when I will list the C: \ files, because it is the root folder and have at least 1 million files and my method is using recursion it give NullPointer. Is there any way to list C: completely in a practical way?

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class PercorrendoArquivosComSubPasta {


    public static void main(String[] args) {
        ArrayList<File> list = (ArrayList<File>) buscaRecursiva(new File("C:\Users\Joel\Desktop\"),".txt");
        for(File i : list) {
            System.out.println(i);
        }
    }

    public static List<File> buscaRecursiva(File dir, String extensao) {

        List<File> listFile = new ArrayList<File>();

        for (File f : dir.listFiles()){
           if (f.isDirectory()) {
               listFile.addAll(buscaRecursiva(f, extensao));

           } else if (f.getName().endsWith(extensao)) {
               listFile.add(f);
           } 
        }
        return listFile;
    }

}

PASTEBIN CODE

    
asked by anonymous 15.04.2018 / 02:11

1 answer

0

Method documentation File.listFiles() :

  

Returns null if this abstract pathname does not denote a directory, or   if an I / O error occurs.

that is, returns null if the path does not represent a directory. What is expected to happen in the case of all files that are not directories.

EDIT: I tested here on Linux and gave NullPointerException when trying to read a folder I was not allowed to read. To do this check in code just use file.canRead() . Example:

import java.io.File;

public class ListFiles {

    public static void main(String [] args) {
        if (args.length > 0) {
            File file = new File(args[0]);
            listar(file);
        }
    }

    private static void listar(File file) {
        System.out.println(file.getAbsolutePath());
        if (file.isDirectory() && file.canRead()) {
            File[] files = file.listFiles();
            for (File f : files) {
                listar(f);
            }
        }
    }
}
    
15.04.2018 / 02:27