我想构建一个数据结构,在其中存储文件系统中的所有文件。 为此,我有一个目录节点类:
class directoryNode{
private String name;
private String path;
File file;
//This List Stores the sub-directories of the given Directory.
private List<directoryNode> subDirectories = new ArrayList<directoryNode>();
//This List stores the simple files of the given Directory
private List<String> fileNames = new ArrayList<String>();
//The Default Constructor.
directoryNode(File directoryName){
this.name = directoryName.getName();
this.path = directoryName.getPath();
this.file = directoryName;
//A Function to build this directory.
buildDirectory();
}
File[] filesFromThisDirectory;
private void buildDirectory(){
//get All the files from this directory
filesFromThisDirectory = file.listFiles();
try{
for(int i = 0 ; i < filesFromThisDirectory.length ; i++){
if(filesFromThisDirectory[i].isFile()){
this.fileNames.add(filesFromThisDirectory[i].getName());
} else if(filesFromThisDirectory[i].isDirectory()){
directoryNode Dir = new directoryNode(filesFromThisDirectory[i]);
this.subDirectories.add(Dir);
}
}
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
我的程序工作正常,但当我不在 buildDirectory() 函数中使用 try-Catch block 时,我会出现一些奇怪的行为。构建函数递归地构建代码中编写的文件列表的结构。
当我这样做时:
directoryNode d1 = new directoryNode(new File("/"));
当 try-Catch 存在时,程序工作正常,但如果我删除 try catch block : 执行一段时间后出现错误:我得到的错误是:
Exception in thread "main" java.lang.NullPointerException
at directoryNode.buildDirectory(myClass.java:47)
at directoryNode.<init>(myClass.java:22)
at directoryNode.buildDirectory(myClass.java:55)
at directoryNode.<init>(myClass.java:22)
at directoryNode.buildDirectory(myClass.java:55)
at directoryNode.<init>(myClass.java:22)
at myClass.main(myClass.java:75)
但是当我运行时:
directoryNode d1 = new directoryNode(new File("/home/neeraj"));
无论有没有try-catch block ,程序都运行良好,没有任何错误。 为什么会这样呢?为什么我在这些场景中得到不同的结果?
最佳答案
问题出在这一行:
filesFromThisDirectory = file.listFiles();
如果 File
对象不是目录,则返回 null...或者如果是目录,但您没有必要的权限。
因此,在进入循环之前,您必须检查 filesFromThisDirectory
是否不为 null。
但帮自己一个忙,放弃 File
并使用 java.nio.file
代替。
关于java - 更好地理解 Java 概念 : File , 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23708705/