Program throws NullPointerException when i try to search in drives?

后端 未结 3 2067
遥遥无期
遥遥无期 2021-01-05 20:24

I wrote a program to find file or directory.
Its working properly when i am trying to Search file with in Directory
example
java FileSea

3条回答
  •  半阙折子戏
    2021-01-05 20:53

    This is how you fix it:

    import java.io.*;
    class FileSearch{
    static String fd;
    static boolean flg=true;
    public static void main(String arr[]){
        fd=arr[0];
        String path=arr[1];
        String dir[]=new File(path).list();
        new FileSearch().finder(dir,path);
        if(flg){System.out.print("File not found.");}
    }
    public void finder(String[] dir,String path){
        if(dir == null){
            return;
        }
        for(int i=0;i

    Why? String dir[]=new File(path).list(); on the directory you specified is null so when you call dir.length you will get null pointer exception

    another thing that will help you understand, System.out.print(new File(path).isDirectory()); if its false, then you will get null pointer exception.

提交回复
热议问题