Program throws NullPointerException when i try to search in drives?

后端 未结 3 2041
遥遥无期
遥遥无期 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 21:05

    list()

    The documentation of listFiles() mentions that it will return null if this abstract pathname does not denote a directory, or if an I/O error occurs. Additionally, you would need to check with file.canRead() whether the application can read the directory.

    IMHO

    Always use it this way;

    String[] files = file.list();
    if (files!=null) {
        for (String f : files) processFile(f);
    }
    

    Recommend this;

    File directory = new File(directoryName);
    
    //get all the files from a directory
    File[] fList = directory.listFiles();
    
    if(fList != null){
        for (File file : fList){
            if (file.isFile()){
                System.out.println(file.getName());
            }
        }
    }
    

    Do let me know if you have any questions.

提交回复
热议问题