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)