【问题标题】:Better Understanding Java Concepts : File , Exception Handling更好地理解 Java 概念:文件、异常处理
【发布时间】: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; PathFiles
  • @fge 它们比旧文件更好吗?

标签: java file exception-handling runtime-error


【解决方案1】:

问题出在这一行:

    filesFromThisDirectory = file.listFiles();

如果File 对象不是目录...或者如果是但您没有必要的权限,这将返回 null。

因此,在进入循环之前,您必须检查 filesFromThisDirectory 是否不为空。

但请帮自己一个忙,放弃 File 并改用 java.nio.file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    相关资源
    最近更新 更多