Exception in thread & ldquo; Hand & rdquo; Java.lang.NullPointerException, no idea what I'm doing wrong

advertisements

getting this error when i want to run it:

Exception in thread "main" java.lang.NullPointerException

at this line

for (File y: childfiles){   )

but strangely enough it depends on the directionary i chose if it works or not

   import java.util.*;
    import java.io.*;
    import java.lang.System;

    public class mainclass {
        public static void main(String[] args) throws IOException, InterruptedException{

    String path = null;
            Scanner scan = new Scanner(System.in);
            System.out.println("enter path:");
            path = scan.nextLine();

    File dir = new File(path);

    File[] files = dir.listFiles();

    for(File x : files){

        System.out.println(x);
        File[] childfiles = x.listFiles();
        for (File y: childfiles){

        if(y.toString().endsWith(".exe")){

           Process p = Runtime.getRuntime().exec(

                   y.toString());
                    p.waitFor();

                    System.out.println(y.toString()+" executed, press enter for next exe");
                    scan.nextLine();

        }
        }

    }

        }
    }


x.listFiles(); will return null for file (not directory)

listFiles()

Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.

So before both of your loop add a nullity check like below

if(files!=null){

}