问题描述
我写了一个程序来查找文件或目录.
当我尝试在 目录
中搜索文件时,它工作正常例子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 Exceptionjava 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()
应用程序是否可以读取目录.
恕我直言
总是这样使用;
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!