我的问题不在于空指针异常。 我的问题是关于为什么在C中进行文件搜索时:我得到了零点异常,即使我可以列出内容。 我做了一个类来搜索文件。 如果我在目录中搜索,一切正常。 但是,如果我在像c或d这样的驱动器中搜索,我会得到一个空指针异常。 我该如何解决这个问题?在Java根目录下搜索文件
下面的代码:
import java.io.File;
import java.util.ArrayList;
/**
* Created by Marcwe on 12/02/2017.
*/
public class FileSearch {
ArrayList<String> listOfResult = new ArrayList<>(10);
public FileSearch(File searchPath, String theFile) {
ArrayList<String> oneList = new ArrayList<>(10);
listOfResult = searchTheFile(theFile, searchPath, oneList);
for (String x : listOfResult) {
System.out.println(x);
}
};
public ArrayList<String> searchTheFile(String theFileToSearch, File inThePath, ArrayList<String> aList) {
File pathToSearch = inThePath;
if (!(inThePath == null)) {
for (File item : pathToSearch.listFiles()) {
if (!(item == null) && !(item.isFile())) {
System.out.println(item.getAbsolutePath());
aList = (searchTheFile(theFileToSearch, item, aList));
} else {
if (!(item == null)) {
if (item.getName().equalsIgnoreCase(theFileToSearch)) {
aList.add(item.getAbsolutePath());
}
}
}
}
}
return aList;
}
public static void main(String[] args) {
FileSearch searchTest = new FileSearch(new File("C:/"), "test.txt");
}
}
告诉我们更多关于错误的信息。 – byxor
可能的重复[什么是NullPointerException,以及如何解决它?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it ) –
您可以使用[适用于JDK的方法]将此代码缩短为几行(https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html #walkFileTree-java.nio.file.Path-java.nio.file.FileVisitor-)。 –