为什么列表保持不变?

时间:2017-03-07 13:19:07

标签: java nio

我尝试创建一个小应用程序,它使用文件walker递归读取文件系统指定位置的内容。我有这段代码:

/* Imports here */

public class App {

    private static Scanner inp;
    public static List<Node> Tree = new ArrayList<Node>();

    public static void main(String[] args) {
        String FFiles;

        System.out.print("Enter root directory: ");
        inp = new Scanner(System.in);

        FileSystem fileSystem = FileSystems.getDefault();
        Path rootPath = fileSystem.getPath(inp.nextLine());

        FileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
              public Path VisitedDirectory = rootPath;
              public List<Node> files = new ArrayList<Node>();


              @Override
              public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs) throws IOException {
                if (dir != VisitedDirectory) {
                    Node directory = new Node(dir.getFileName().toString(), "directory", files, dir.toString());
                    files.add(directory);
                    Node VisDirectory = new Node(VisitedDirectory.getFileName().toString(), "directory", files, dir.toString());
                    Tree.add(VisDirectory);

                    files.clear();
                }
                return FileVisitResult.CONTINUE;
              }

              @Override
              public FileVisitResult visitFile(Path visitedFile,BasicFileAttributes fileAttributes) throws IOException {
                Node file = new Node(visitedFile.getFileName().toString(), "file", null, visitedFile.toString());
                files.add(file);
                return FileVisitResult.CONTINUE;
              }
        };



        try {
            Files.walkFileTree(rootPath, simpleFileVisitor);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

        for (Node n : Tree) {
            System.out.println(n);
        }
    }

这就是问题所在:为什么只读取(显示)目录? P.S Node类只是几个变量并且声明如下:

public class Node {
    @Override
    public String toString() {
        return "Node [path=" + path + "]";
    }

    public String name;
    public String path;
    public  String type;
    public List<Node> children = new ArrayList<Node>();
    public Node(String name, String type, List<Node> children, String path) {
        this.name = name;
        this.type = type;
        this.children = children;
        this.path = path;
    }
}

1 个答案:

答案 0 :(得分:0)

你正在使用files列表搞得一团糟。您只创建一个实例。因此,您的new Node(VisitedDirectory.getFileName().toString(), "directory", files, dir.toString())实际上并不复制文件列表,而只是存储引用。您的files.clear()来电将清除您拥有的所有文件列表。这就是为什么只有你添加到Tree的节点才能存活下来。

请将Tree重命名为小写。这样就可以认为Tree.add()Tree类上调用静态方法。