简体   繁体   English

获取文件树时出错

[英]Error getting file tree

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FileTree {
    List<File> file_list = new ArrayList<File>();

    public List<File> getTree(String root)
    {
        File f = new File(root);
        ArrayList<File> tmp = new ArrayList<File>(Arrays.asList(f.listFiles()));

        for(int i = 0; i < tmp.size(); i++)
        {
            f = tmp.get(i);
            if(f.isFile())
                file_list.add(f);
            else if(f.isDirectory()) 
                getTree(root + "\\" + f.getName());
        }

        return file_list;
    }
}

Error: 错误:

  Exception in thread "main" java.lang.NullPointerException
        at java.util.Arrays$ArrayList.<init>(Arrays.java:2842)
        at java.util.Arrays.asList(Arrays.java:2828)
        at FileTree.getTree(FileTree.java:12)
        at FileTree.getTree(FileTree.java:22)
        at Server.main(Server.java:10)

I'm trying to get a list of files from a directory (root). 我正在尝试从目录(root)获取文件列表。 The code was working until I tried to access subfoders. 代码工作,直到我尝试访问子代码。 What is the problem here? 这里有什么问题?

The method File#listFiles() yields null if the file object (f) does not denote a directory (or if an I/O-error occurs). 如果文件对象(f)不表示目录(或者发生I / O错误),则File#listFiles()方法产生null

So before you call f.listFiles() you should first check if f represents a directory - your input root might not be directory. 因此,在调用f.listFiles()之前,首先应检查f代表目录 - 您的输入root可能不是目录。 You can use this method: File#isDirectory() and then adjust your logic. 您可以使用此方法: File#isDirectory()然后调整您的逻辑。 Or: You have not got granted access privileges for one given subdirectory. 或者:您没有被授予一个给定子目录的访问权限。 In this case you might check readability by using the method canRead() (and don't forget to debug f.getName() and then to find out if you have enough access rights). 在这种情况下,您可以使用canRead()方法检查可读性(并且不要忘记调试f.getName()然后找出您是否有足够的访问权限)。

Form a listFiles of java.io.File documentation: 形成一个java.io.File文档的listFiles

Returns: An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. 返回:一个抽象路径名数组,表示此抽象路径名表示的目录中的文件和目录。 The array will be empty if the directory is empty. 如果目录为空,则数组将为空。 Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs. 如果此抽象路径名不表示目录,或者发生I / O错误,则返回null。

I see you're checking if file actually is directory, despite first call on root. 我看到你正在检查文件是否实际上是目录,尽管首先调用root。 What might cause your problem then are I/O errors like permission denied for example. 那么可能导致您的问题的是I / O错误,例如拒绝权限。 Also the way how you create root path string might cause problems on different file systems, try changing this line 此外,创建根路径字符串的方式可能会导致不同文件系统出现问题,请尝试更改此行

getTree(root + "\\" + f.getName());

into

getTree(f.getAbsolutePath());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM