S
S
SoloCheater2018-08-10 23:20:44
Java
SoloCheater, 2018-08-10 23:20:44

How to get a list of all files relative to a disk in Java?

Hello. I have below code:

private static ArrayList<String> fileList = new ArrayList<String>();
  
    public static void main(String[] args) throws IOException, InterruptedException, ParserConfigurationException, ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
    	displayAll(new File("D://"));
    	PrintWriter out = new PrintWriter(C://test.txt);
    	for (String fileName : fileList) {
    	   out.println(fileName);
    	}
    }

    public static void displayAll(File path){      
        if(path.isFile()){
        	fileList.add(path.getAbsolutePath());
        }else{
        	fileList.add(path.getAbsolutePath());       
            File files[] = path.listFiles();
            for(File dirOrFile: files){
                displayAll(dirOrFile);
            }
        }
    }

When starting the program, an error appears in the console:
Exception in thread "main" java.lang.NullPointerException
  at ru.fixer.Main.displayAll(Main.java:75)
  at ru.fixer.Main.displayAll(Main.java:76)
  at ru.fixer.Main.displayAll(Main.java:76)
  at ru.fixer.Main.main(Main.java:61)

If you change the path from new File("D://") to new File ("D://Desktop"), then a list of all files is quietly displayed.
What needs to be changed so that the path is from the disk, and not from the folder in the disk?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question