0

///EDIT/// The Question Is Not Asking What A Null Pointer Exception Is, Merely What Might Have Caused It In This Instance. As Such IS NOT A Duplicate Of The Post Linked.

Im trying to search the entire system for any mp3 or wav files. If I use the algorithm for a small tree such as the users desktop it works fine, but if I go for a larger tree such as the users home directory it throws a null pointer exception. Anyone know how I can get around this?

package audioTest;

import java.io.File;


public class Main {


    public static void recListFile(File[] list){
        for(File i : list ){
            if(i.isDirectory()){
                recListFile(i.listFiles());
            }
            else{
                String filePath = i.toString();
                StringfileExt=filePath.substring(filePath.lastIndexOf(".")+1);
                if(fileExt.equals("wav") || fileExt.equals("mp3")){
                    System.out.println(i.getName());
                }
            }
        }
    }//end recListFile


    public static void main(String[] args){

        File dir = new File(System.getProperty("user.home"));
        try {
            recListFile(dir.listFiles());
        } catch(NullPointerException n) {
            // more general: catch(Error n)
            // anything: catch(Throwable n)
            System.out.println("Caught "+n);
            n.printStackTrace();
        }
    }
}

Here is the exception and stack trace

Exception in thread "main" java.lang.NullPointerException
    at audioTest.Main.recListFile(Main.java:11)
    at audioTest.Main.recListFile(Main.java:13)
    at audioTest.Main.recListFile(Main.java:13)
    at audioTest.Main.recListFile(Main.java:13)
    at audioTest.Main.main(Main.java:30)
Philip Butler
  • 479
  • 1
  • 5
  • 13

1 Answers1

0

That is not a safe operation for an array. for(File i : array){

and the list is something you are trying to get from a File: See the tooltip

file.listFiles():

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.


Working with List interface is safer and you can convert your array of File[] to list by using this:

List<File> fileList = Arrays.asList($yourArrayHere$);


strash
  • 1,291
  • 2
  • 15
  • 29