2016-07-01 11 views
0

ファイルディレクトリとその中のサブディレクトリとファイルを解析する必要があるという要件があります。さらに私は、これらのディレクトリ内のファイルサイズの統計のいくつかを行うと、二つの画面上で結果を視覚化する必要があります。ファイルディレクトリを模擬するデータ構造

1)ディレクトリ、サブディレクトリやファイル(サイズ> 50メガバイト)

とフォルダツリー2)ファイル構造を解析することで、すぐに結果を印刷するディレクトリとフォルダツリー、サブディレクトリやファイル(サイズ< 50メガバイト)

は簡単ですが、私は、私が覚えて任意のデータ構造を考えることはできませんその中のディレクトリとサブディレクトリとファイル。

これは私がすでにディレクトリを解析するために実装したものです:

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のなステートメントを書かれているところ、私は、ディレクトリとそのサブディレクトリとファイルを格納できるデータ構造を使用したいとそれらのサブディレクトリ内のファイル
ありがとうございます。

+3

これは、[ツリー](https://docs.oracle.com/javase/tutorial/uiswing/components/tree.html)のようなものですか? – Tom

+1

'FileSystem'、' File'、 'Path'などのJDK抽象化を直接使うことを考えましたか? –

+0

@tomはい、正確です。しかし、いくつかの基準に基づいてフィルタリングされた2つのビューが存在します。 –

答えて

0

データ構造のようなツリーは、問題に適しています。スイングツリーノードのようにLinkedListTreeMap、またはTreeNodeである可能性があります。

で始まるJava 7を使用すると、FileVisitorを使用して内部構造/ビューモデルを構築してフィルタすることができます。

次の簡単な例では、FileVisitorは、一部のディレクトリのビューモデルを構築するために使用されます。 FilePathNodeは、java.nio.file.Pathオブジェクト用のアダプタです。私はあなたがフィルタロジックを追加することができるいくつかのコメントを入れました。この例では、2番目のビュー/モデルの1つの画面と2番目のビューモデルの2番目の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); 

    } 
} 
関連する問題