統計檔案數目

cheunghr發表於2021-01-15
public class FileTypeCount {
    int white = 0;
    int other = 0;
    LinkedList<String> whiteFileList = new LinkedList<>();
    LinkedList<String> otherFileList = new LinkedList<>();
    String[] whiteList = {"java", "jsp"};

    @Test
    public void scanFileType() {
        String path = "C:\\Users\\beix\\Desktop\\yk";
        recursionScan(path);
        System.out.println(Arrays.toString(whiteList) + " count:" + white);
        System.out.println("other file count:" + other);
    }

    public void recursionScan(String basePath) {
        List<String> whiteArray = Arrays.asList(whiteList);
        File file = new File(basePath);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    if (!f.isDirectory()) {
                        String fileName = f.getName();
                        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
                        if (whiteArray.contains(fileType.toLowerCase())) {
                            whiteFileList.add(f.getAbsolutePath());
                            white++;
                        } else {
                            otherFileList.add(f.getAbsolutePath());
                            other++;
                        }
                    } else {
                        recursionScan(f.getAbsolutePath());
                    }
                }
            }
        }
    }
}

相關文章