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

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

问题描述

我写了一个程序来查找文件或目录.
当我尝试在 目录
中搜索文件时,它工作正常例子
java FileSearch abc.txt f:xyz
但是当我尝试从本地驱动器搜索文件而不是程序抛出异常
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.

推荐答案

列表()

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.

恕我直言

总是这样使用;

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天全站免登陆