用于模拟文件目录的数据结构

时间:2016-07-01 16:29:41

标签: java

我有一个要求,我必须解析文件目录及其子目录和文件。此外,我必须对这些目录中的文件大小进行一些统计,并在两个屏幕上显示结果:

1)包含目录,子目录和文件的文件夹树(大小> 50 mb)

2)包含目录,子目录和文件的文件夹树(大小<50 mb)

通过解析文件结构立即打印结果很容易,但我无法想到任何可以记住其中的目录和子目录及文件的数据结构。

这是我已经实现的用于解析目录的内容:

    public void listFilesAndFilesSubDirectories(String directoryName) {
    File directory = new File(directoryName);
    //get all the files from a directory
    File[] fList = directory.listFiles();
    for (File file : fList) {
        if (file.isFile()) {
            System.out.println(file.getAbsolutePath() + "    " + file.length() / 1024);
            countWords(file.getAbsolutePath());
            findRepeatedWords(file.getAbsolutePath());
        } else if (file.isDirectory()) {
            listFilesAndFilesSubDirectories(file.getAbsolutePath());
        }
    }
}

我写过Sysout语句的地方,我想使用一个数据结构,我可以在那里存储目录及其子目录以及这些子目录中的文件和文件。
谢谢你的期待。

1 个答案:

答案 0 :(得分:0)

任何树状数据结构都适合您的问题。这可能是Swing TreeNodes的LinkedListTreeMapTreeNode

Java 7 开始,您可以使用FileVisitor构建和过滤内部结构/视图模型。

在下面的简单示例中,FileVisitor用于构建视图模型,某个目录的视图模型。 FilePathNodejava.nio.file.Path对象的适配器。我已经添加了一些注释,您可以在其中添加过滤器逻辑。该示例仅显示第二个屏幕/视图的一个屏幕,第二个JTree元素具有第二个视图模型。

package filetreeexamle;

import java.awt.BorderLayout;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;


public class FileTreeSwingUIExample {


    @SuppressWarnings("serial")
    private static class FilePathNode extends DefaultMutableTreeNode {

        // store additional stuff like used diskspace (for directories and files)


        public FilePathNode(Path path) {
            super(path);
        }

        @Override
        public void add(MutableTreeNode newChild) {
            if (((Path)getUserObject()).toFile().isFile()) 
                throw new IllegalArgumentException("Can't add a child node to a file.");
            super.add(newChild);
        }

        @Override
        public boolean isLeaf() {
            return ((Path)getUserObject()).toFile().isFile();
        }   

    }   

    private static class TreeViewControllerDelegate {
        private JTree treeView;

        private static class FileTreeBuilder implements FileVisitor<Path> {

            // node where the builder starts 
            // contains the whole subtree after processing the whole tree
            FilePathNode rootNode;

            // temporary reference to the directory currently processed.
            private FilePathNode currentDir;                

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {

                currentDir = new FilePathNode(dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                FilePathNode fileNode = new FilePathNode(file);
                // here you can add filter conditions for files
                // also you may update the consumed disk space of the parent directory
                currentDir.add(fileNode);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                if (exc != null) throw exc;
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (exc != null) throw exc;

                // here you can filter directories like directories
                // which use more than n MB of diskspce.

                if (rootNode == null) {
                    rootNode = currentDir;
                } else {
                    rootNode.add(currentDir);
                }
                return FileVisitResult.CONTINUE;
            }


        }

        public TreeViewControllerDelegate(JTree treeView) {
            this.treeView = treeView;
        }

        public void load(Path path) {           

            FileTreeBuilder builder = new FileTreeBuilder();
            try {
                Files.walkFileTree(path, builder);
                treeView.setModel(new DefaultTreeModel(builder.rootNode) );
                treeView.repaint();
            } catch (IOException ioe) {
                JOptionPane.showMessageDialog(null,
                        "Failed to load file strucutre",
                        "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }

    }

    public static void main(String ... args) {


        JFrame mainWindow = new JFrame("Sample File Tree View");
        JTree fileTree = new JTree();

        TreeViewControllerDelegate controller = new TreeViewControllerDelegate(fileTree);
        controller.load(Paths.get("."));

        mainWindow.getContentPane().setLayout(new BorderLayout());
        mainWindow.add(fileTree, BorderLayout.CENTER);
        mainWindow.setSize(200, 300);
        mainWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        mainWindow.setVisible(true);

    }
}