0

I would like to list out files of all folders which are having all type of files like hidden,non-permissible and normal files etc. and it needs to be done all platforms like windows,linux and mac. I wrote a snippet in java to figure out it but it is able to print only normal files.When the execution comes to non-permissible file it throws an exception stating NullPointerException and execution gets stopped.Is there any way to traverse through the folders with root permissions?.

public static void main(String[] args) throws IOException {
             File[] drives;
                FileSystemView fsv = FileSystemView.getFileSystemView();
             // returns pathnames for files and directory
                drives = File.listRoots();

             // for each pathname in pathname array
                if (drives != null && drives.length > 0) {
                    for (File aDrive : drives) {
                        System.out.println("Drive Letter: " + aDrive);

                        listFilesAndFilesSubDirectories(aDrive.toString());
                    }
                }


        }

        private static void listFilesAndFilesSubDirectories(String filePath) {
            // TODO Auto-generated method stub
            File directory = new File(filePath);
            File[] fList = directory.listFiles();
            for (File file : fList){
                if (file.isFile()){
                    System.out.println(file.getAbsolutePath()+"\n**************************");

                } else if (file.isDirectory()){
                    listFilesAndFilesSubDirectories(file.getAbsolutePath());
                }
            }
        }

and the exception it throws is below

Exception in thread "main" java.lang.NullPointerException
    at com.dlp.Test.listFilesAndFilesSubDirectories(Test.java:35)
    at com.dlp.Test.listFilesAndFilesSubDirectories(Test.java:40)
    at com.dlp.Test.listFilesAndFilesSubDirectories(Test.java:40)
    at com.dlp.Test.listFilesAndFilesSubDirectories(Test.java:40)
    at com.dlp.Test.main(Test.java:24)

Kindly help me to overcome this issue. Thanks.

Shekhar
  • 39
  • 7
  • 1
    `directory.listFiles();` can return `null`. Repair that. – Joop Eggen Nov 02 '17 at 11:44
  • Thanks for the reply Joop..If i handle null for a folder which is having files but not permissible,I can not traverse through that folder. But my intention is to traverse through even not permissible folders and hidden files. – Shekhar Nov 02 '17 at 12:32
  • Maybe java 8's new `Files.list(Path)` brings more, but I doubt it. Certainly the not permisible subdirectories. Maybe ProcessBuilder with dir resp. sudo ls is needed. Good luck – Joop Eggen Nov 02 '17 at 13:17

0 Answers0