【发布时间】:2014-05-17 07:19:12
【问题描述】:
我想构建一个数据结构,用于存储文件系统中的所有文件。 为此,我有一个类 directoryNode:
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 块时,我得到了一些奇怪的行为。构建函数递归地构建代码中编写的文件列表的结构。
当我这样做时:
directoryNode d1 = new directoryNode(new File("/"));
当 try-Catch 存在时,程序可以正常工作,但如果我删除 try catch 块: 执行一段时间后出现错误:我得到的错误是:
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 块,我的程序运行良好,没有任何错误。 为什么会这样?为什么在这些情况下我会得到不同的结果?
【问题讨论】:
-
buildDirectory() 函数中的for循环
-
你为什么使用
File?你还在使用 Java 6 吗? -
@fge 只是好奇,Java 7/8 的更好选择是什么?
-
@user3580294 java.nio.file;
Path、Files等 -
@fge 它们比旧文件更好吗?
标签: java file exception-handling runtime-error