2012-09-03 35 views
12

我使用下面的Apache的百科全書類上市文件的文件系統上使用Java:我可以檢查一個集合的大小被填充了

Collection<File> allFiles = FileUtils.listFiles(rootDirectory, null, recursive);

這是一個非常漫長的過程,最多可能需要5分鐘。

有沒有什麼辦法可以檢查集合的大小

我試圖從一個單獨的線程訪問它,但直到該過程準備就緒,直到零。

回答

2

你可以使用文件實用程序IOFileFilter。

Collection<File> listFiles = FileUtils.listFiles(new File("."), counter, FileFilterUtils.trueFileFilter()); 

其中計數器將是沿着線

IOFileFilter counter = new IOFileFilter() { 

    @Override 
    public boolean accept(File arg0, String arg1) { 
     countCall(); 
     return true; 
    } 

    @Override 
    public boolean accept(File arg0) { 
     countCall(); 
     return true; 
    } 
}; 

和countCall是更新進度的方法。

+0

這非常有創意。我會嘗試並回復你 – Redandwhite

11

在從方法中獲取返回值之前,您將無法訪問集合,因爲您無法訪問此方法在內部使用的變量。

您可以通過不使用遞歸標誌來分割小塊中的搜索,並自己處理遞歸以接收每個目錄的集合。

如果您使用Java 7,更好的選擇是使用the FileVisitor interface to explore the file system。它有幾個回調方法可以讓你跟蹤進度。

+0

+1提FileVisitor的和回調 – Pyranja

+0

不幸的是,我不得不使用Java 6,因爲應用程序需要與內置的JVM的Mac上工作(蘋果仍然船舶的Java 6!) – Redandwhite

+0

@Redandwhite我認爲你唯一的選擇就是分裂搜索 - 除非有人提出了一個更好的主意。 – assylias

1

我想你可以嘗試使用執行特定於平臺的命令,如重定向列表命令輸出到臨時文件並使用Java File API讀取它。

ls > temp.txt

我創建了一個簡單的shell腳本將在給定的索引列表文件。

#!/bin/bash 

RANGE_UP=$2 
RANGE_BOT=$1 

CURRENT_CNTR=0 

FILENAME=._m_ls 

ls -w 1 > $FILENAME 
while read line 
do 
    if [ $CURRENT_CNTR -le $RANGE_UP -a $CURRENT_CNTR -gt $RANGE_BOT ]; then 
    printf $line"\n" 
    fi 
    CURRENT_CNTR=`expr $CURRENT_CNTR + 1` 
done < $FILENAME 

你現在可以做這樣的事情./ls_range.sh 10000 30000 >temp.txt,然後從不同的線程使用BufferedReader讀取這個文件。

1

你唯一的方法來做到這一點(而不是java7或像以前建議的那樣拆分工作)將會編寫自己的代碼,在更新回調的同時搜索整個文件系統。

我使用了commons-io的代碼,並對其進行了修改以適應您的需要,顯然它需要測試,但是它會在發現文件時對其進行計數。

interface Counter { 
    void foundFile(File file); 
} 

final class FileSearcher { 
    public static Collection<File> listFiles(File root, FileFilter filter, Counter counter) { 
     Collection<File> files = new ArrayList<File>(); 
     File[] found = root.listFiles(filter); 

     if (found != null) { 
      for (int i = 0; i < found.length; i++) { 
       if (found[i].isDirectory()) { 
        files.addAll(listFiles(found[i], filter, counter)); 
       } else { 
        files.add(found[i]); 
        counter.foundFile(found[i]); 
       } 
      } 
     } 

     return files; 
    } 
} 

,然後用它是這樣的:

final AtomicInteger inte = new AtomicInteger(0); 
FileSearcher.listFiles(new File("C:/"), null, new Counter() { 
    @Override 
    public void foundFile(File file) { 
     System.out.println("found file number " + inte.addAndGet(1)); 
    } 
}); 
相關問題