2011-09-27 68 views
2

我想顯示所有文件和每個文件的根目錄下的目錄下的遞歸顯示所有文件和每個文件的根文件夾遞歸

輸出應該是這樣的

文件名--->其中包含文件的目錄

例如 filename.jpg ---> C:\工作區

的filename.jpg是在C:\工作區,即:路徑爲c :\ workspace \ filename.txt存在ar E在每個目錄

+1

你嘗試過什麼? java.io.File類具有實現這一點所需的一切。見http://download.oracle.com/javase/6/docs/api/java/io/File.html –

+0

首先谷歌命中['遞歸文件列表'](http://www.javapractices.com/topic/ TopicAction.do?Id=68) – JRL

回答

4

請記住,具有相同名稱的文件名,將在該解決方案中重寫許多文件(你需要一個Map<String, List<File>>允許此):

public static void main(String[] args) throws Exception { 

    Map<String, File> map = getFiles(new File(".")); 

    for (String name : map.keySet()) 
     if (name.endsWith(".txt")) // display filter 
      System.out.println(name + " ---> " + map.get(name)); 
} 

private static Map<String, File> getFiles(File current) { 

    Map<String, File> map = new HashMap<String, File>(); 

    if (current.isDirectory()) { 
     for (File file : current.listFiles()) { 
      map.put(file.getName(), current); 
      map.putAll(getFiles(file)); 
     } 
    } 

    return map; 
} 

輸出示例:

test1.txt ---> . 
test2.txt ---> .\doc 
test3.txt ---> .\doc\test 
+0

我想只顯示特定擴展名的文件我該如何做? – pavan

+1

@pavan更新了答案(請參閱顯示過濾器) – dacwe

0

您可以使用Apache Commons Fileutils

public static void main(String[] args) throws IOException { 
    File rootDir = new File("/home/marco/tmp/"); 
    Collection<File> files = FileUtils.listFiles(rootDir, new String[] { 
      "jpeg", "log" }, true); 
    for (File file : files) { 
     String path = file.getAbsolutePath(); 
     System.out.println(file.getName() + " -> " 
       + path.substring(0, path.lastIndexOf('/'))); 
    } 
} 

第一個參數listFiles是要從中開始搜索的目錄,第二個參數是String的數組,第三個參數是boolean,表示搜索是否遞歸搜索。

輸出示例:

visicheck.jpeg -> /home/marco/tmp 
connettore.jpeg -> /home/marco/tmp 
sme2.log -> /home/marco/tmp/sme2_v2_1/log 
davmail_smtp.jpeg -> /home/marco/tmp 
相關問題