这是一个在文件夹下搜索给定文件,并且返回路径的代码,工程一部分:
public static String SearchFile(String directory,String filename)
{
File absolutePath = new File(directory);
if(!absolutePath.exists())
{
System.out.println("找不到指定的路径,请重新指定!");
return null;
}else
{
if(absolutePath.isDirectory())
{
File[] filelist = absolutePath.listFiles();
for(File f: filelist)
{
String result = SearchFile(f.toString(),filename);
if(result != null)
return result;
}
return null;
}
else
{
if(filename.equals(absolutePath.getName()))
return absolutePath.getPath();
else
{
return null;
}
}
}
}算法使用了递归。但我在测试时有的时候情况很顺利(比如在F盘),有的时候(换了其他盘之后)在红字处会出现NullPointerException。。十分诡异求达人指点~

解决方案 »

  1.   

    listFiles()方法返回null:    public File[] listFiles() {
    String[] ss = list();
    if (ss == null) return null;
    int n = ss.length;
    File[] fs = new File[n];
    for (int i = 0; i < n; i++) {
        fs[i] = new File(ss[i], this);
    }
    return fs;
        }调用的list():
        public String[] list() {
    SecurityManager security = System.getSecurityManager();
    if (security != null) {
        security.checkRead(path);
    }
    return fs.list(this);
        }
      

  2.   

    看看jdk里面关于ListFile返回值的说明:
    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.有两种情况可以回返回null
    1)父路径不是文件夹。
    2)出现IO错误。
    从你的代码来看,你的程序是由于IO错误导致的。你看看磁盘的权限、或指定的文件夹是否被别的进程锁死了,可以把出错的文件路径输出来看看.