我想統計一個目錄中有多少圖像。我有一個來自互聯網的代碼副本,它可以檢測目錄中的全部文件。計算目錄中的圖像
import java.io.*;
public class CountFilesInDirectory {
public static void main(String[] args) {
File f = new File("/home/pc3/Documents/ffmpeg_temp/");
int count = 0;
for (File file : f.listFiles()) {
if (file.isFile()) {
count++;
}
}
System.out.println("Number of files: " + count);
}
}
我想計算一個特定的文件類型,如jpg/txt。我該怎麼辦?
感謝您的幫助..它工作得非常,我可以與其他部分繼續。 。再次感謝您的幫助。 – Eric 2012-04-18 01:44:03
儘管技術上正確,但我不同意這種解決方案。我將使用'java.io.FilenameFilter'的實現並將它傳遞給'File.listFiles(FilenameFilter)'方法,以僅返回與Pattern匹配的文件(或者使用'String.endsWith(String)')。這個解決方案嗅到程序代碼,而不是OO。 – 2012-04-18 02:39:09
@JohnGaughan - 基於OP的代碼,這似乎是修改它以獲得預期結果的最簡單方法 – Attila 2012-04-18 02:41:06