0

so I'm learning java right now and have seen numerous examples of this same question, but the answers mostly have to do with Android permissions people needed to add. In my case, I have tested that my program has access to the given directory. The System.out's print out Arrays with all of the files and directories in it, but for some reason the files variable finds that fileList is null. Thanks in advance

    package com.assignment3;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

public class FileFinder {
    ArrayList<String> folders = new ArrayList<>();
    public void find(ArrayList<String> args){
        if (args.size() > 0){
            File file = new File(args.get(0));
            System.out.println(file);
            String[] fileList = file.list();
            assert fileList != null;
            String[] files = new String[fileList.length - 1];
            if (files.length - 1 >= 0) System.arraycopy(fileList, 0, files, 0, files.length - 1);
            System.out.println(Arrays.toString(file.list()));
            System.out.println(Arrays.asList(files));

            for (String f : fileList){
                int ext = f.lastIndexOf(".");
                if (ext > 0){
                    System.out.println(f);
                } else {
                    folders.add(f);
                }
        }
            if (folders.size() > 0){
                find(folders);
                folders.remove(0);
            } else {
                System.out.println("All files listed.");
            }
        } else {
            System.out.println("You need to add a directory to command line arguments.");
            System.exit(0);
        }
    }

}
CarterDev
  • 9
  • 2
  • Please show the NPE's stack trace (the exception's error message) and indicate exactly which line throws it. – Hovercraft Full Of Eels Apr 17 '22 at 19:27
  • Also, are you making sure that the args parameter contains an appropriate object with data. – Hovercraft Full Of Eels Apr 17 '22 at 19:28
  • 1
    java.io.File is a very old class that doesn’t report errors well. Remove all use of File, and instead create a Path using [Paths.get](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/nio/file/Paths.html#get(java.lang.String,java.lang.String...)), then pass it to [Files.newDirectoryStream](https://docs.oracle.com/en/java/javase/18/docs/api/java.base/java/nio/file/Files.html#newDirectoryStream(java.nio.file.Path)) in order to list the directory. Either it will work, or you will get an exception which is much easier to act on than just “a method returned null.” – VGR Apr 17 '22 at 20:57

0 Answers0