0

I am writing a GUI program with java FX. The user can choose any directory in system. Unfortunately, directory chooser let the user choose a drive too. We can list out all files and folders in a directory using file.listFiles(). What happens if a user choose a drive. The listfiles() is failing there with null pointer exception.

Is there any way i can get the list of files and directories in a drive in java?

    //Get files from the user computer
    public void getFileNames(File folder) {
        for (final File file : folder.listFiles()) {
            if (file.isDirectory()) {
                getFileNames(file);
            } else {
                if (FilenameUtils.isExtension(file.getName().toLowerCase(), videoFormatSet)) {
                    //Don't consider video files less than 100 MB
                    final Long FileSizeInMB = file.length() / 1048576;
                    if (FileSizeInMB < 100) {
                        continue;
                    }
                    final String fileName = FilenameUtils.removeExtension(file.getName());
                    if (!movieNameFilter(fileName).isEmpty()) {
                        movieFileNameList.add(movieNameFilter(fileName));
                    } else {
                        movieFileNameList.add(fileName);
                    }
                }

Edit:

The code lets a user chooses a directory (folder variable). The getFileNames() extract all the movie file Name in the chosen directory. The code is working fine when the user is selecting a directory.

But,JavaFx lets the user select a drive as well (i am using directory chooser). Lets say for example, he chooses c drive (c:) in the system.

The value of file folder = E:\

The null pointer exception is happening when i am doing folder.listFiles() in 171st line

    171: for (final File file : folder.listFiles()) {

I can avoid this by adding a validation for not letting user chose a drive.

But if i want to let him choose a drive. Is there any way i can get list of all files in that drive?

Simply put, is it possible to write a code which lets user provide a drive (Ex: C or D) so that it can display all files in that drive.

Stack Trace:

Exception in thread "Thread-5" java.lang.NullPointerException at com.imdbrater.application.JavaFXApplication$GetfilesThread.getFileNames(JavaFXApplication.java:171) at com.imdbrater.application.JavaFXApplication$GetfilesThread.getFileNames(JavaFXApplication.java:173) at com.imdbrater.application.JavaFXApplication$GetfilesThread.getFileNames(JavaFXApplication.java:173) at com.imdbrater.application.JavaFXApplication$GetfilesThread.run(JavaFXApplication.java:167) at java.lang.Thread.run(Unknown Source)

Rahul Kurup
  • 693
  • 3
  • 9
  • 22
  • Did you try debugging it to see exactly where it gets the NPE? – Bruno Toffolo Apr 01 '15 at 16:11
  • 1
    Can we see the stack trace? Which line is throwing the NPE? – But I'm Not A Wrapper Class Apr 01 '15 at 16:15
  • your code throws a NPE every time the program doesn't have sufficient rights to perform a directory listing. – muued Apr 01 '15 at 16:27
  • Since you're using JavaFX, I assume you're using Java 7 or later. Which means you should not be using the java.io.File class at all, as its reporting of errors is poor. Use [Path](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html) and [Files](http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html) instead. To recursively list files, use one of the `walkFileTree` methods of Files (or `walk` if you're using Java 8). – VGR Apr 01 '15 at 16:43
  • Added the exact reason for NPE. @VGR: yes. I am using java 8. Thanks for the suggestion.Yes it makes more sense to use walkfileTree. – Rahul Kurup Apr 02 '15 at 04:28
  • Loading every file seems like a rather bad thing to do. Have you tried [setting a FileSystemView](http://stackoverflow.com/questions/32529/how-do-i-restrict-jfilechooser-to-a-directory)? I'd imagine they incorporated this to JFX. – Obicere Apr 02 '15 at 04:53

1 Answers1

2

I noticed you performed some calls to different movieNameFilter() method, that was not declared in the piece of code you posted. Please make sure that this method is returning a correct value, as you call some methods on the returning objects.

You didn't post where the NullPointerException is happening, so I will base my answer on a simple and possible null output on the operation you are trying to perform. Please be sure that the drive input by the user actually exists. As can be seen in the API documentation for java.io.File,

Returns:

An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

In this case, if your user inputs a path that does not exist, you will get an NPE.

The best approach to handle this would be to firstly validate the user input. A secondary step involves validating the output of your listFiles() call.

// Get files from the user computer
public void getFileNames(File folder) {

    // retrieve file listing
    File[] fileList = folder.listFiles();

    if (fileList == null) {
        // throw an exception, return or do any other error handling here
        return;
    }

    // path is correct
    for (final File file : fileList ) {
        // etc etc etc
    }
}

If the NPE is related to any other error, please comment so I may update my answer accordingly.


Note: Please remember that filepaths in Java are escaped with double backslashes, so you should make your call in a way such as follows.

File rootFolder = new File("C:\\");
getFileNames(rootFolder);

File downloadsFolder = new File("C:\\Users\\Rahul\\Downloads");
getFileNames(downloadsFolder);
Bruno Toffolo
  • 1,504
  • 19
  • 24
  • The movieFilter function is just for cleaning the movieFile names.That function is not causing the NPE.The NPE is happening while doing listFiles() for a drive. File rootFolder = new File("C:\\"); getFileNames(rootFolder); will result in NPE. Is there any way to list out files in a drive? – Rahul Kurup Apr 02 '15 at 04:31
  • Hi Rahul, thanks for detailing. Didn't my solution work? Or you didn't test it? =( – Bruno Toffolo Apr 02 '15 at 14:04
  • No.Unfortunately.It didn't work..Its still throwing NPE when trying listFiles() on the file. – Rahul Kurup Apr 03 '15 at 05:13
  • Ok. Could you debug the code to see in which line the NPE occurs? – Bruno Toffolo Apr 03 '15 at 12:38