当我尝试在驱动器中搜索时,程序抛出NullPointerException? [英] Program throws NullPointerException when i try to search in drives?

查看:115
本文介绍了当我尝试在驱动器中搜索时,程序抛出NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个程序来查找文件或目录。

当我尝试使用目录搜索文件时,它正常工作


示例

java FileSearch abc.txt f:\ xyz

但是当我尝试从本地驱动器<搜索文件时/ strong>比程序抛出异常

java FileSearch abc.txt f:\
显示所有搜索结果都抛出NullPointerException。

I wrote a program to find file or directory.
Its working properly when i am trying to Search file with in Directory
example
java FileSearch abc.txt f:\xyz
But when i am try to search file from local drive than program throw Exception
java FileSearch abc.txt f:\
after Showing all the search result throws NullPointerException.

代码是:

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){
    for(int i=0;i<dir.length;i++){
        if(dir[i].equals(fd)){
            System.out.println(path+"\\"+fd);
            flg=false;
        }
        if(new File(path,dir[i]).isDirectory())
            finder(new File(path,dir[i]).list(),path+"\\"+dir[i]);
    }   
}
}

我想知道为什么会这样异常被抛出,我该如何解决它。

I want to know why this exception is thrown and how can i fix it.

推荐答案

list()


listFiles()的文档提到它将返回 null
如果此抽象路径名不表示目录,或者发生I / O
错误。此外,您需要使用
file.canRead()检查应用程序是否可以读取目录。

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.

恕我直言

始终以这种方式使用;

Always use it this way;

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

推荐这个;

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.

这篇关于当我尝试在驱动器中搜索时,程序抛出NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆