统计文件夹下所有文件的字数

统计文件夹下所有.md文件的字数

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.regex.Pattern;

public class WordCounter {
    private static final Pattern WORD_PATTERN = Pattern.compile("[a-zA-Z]+|[\u4e00-\u9fa5]");
    private static long totalWords = 0;

    public static void main(String[] args) throws IOException {
        Path startPath = Paths.get("path/to/your/directory"); // replace with your directory
        Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toString().endsWith(".md")) {
                    totalWords += countWords(file);
                }
                return FileVisitResult.CONTINUE;
            }

            private long countWords(Path file) throws IOException {
                long count = 0;
                try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        count += WORD_PATTERN.split(line).length;
                    }
                }
                return count;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
                System.out.println("Visited directory: " + dir + ", total words: " + totalWords);
                return FileVisitResult.CONTINUE;
            }
        });
        System.out.println("Total words in all .md files: " + totalWords);
    }
}

相关推荐

  1. 统计文件夹所有文件字数

    2024-03-25 10:10:06       20 阅读
  2. 递归读取文件夹所有文件

    2024-03-25 10:10:06       28 阅读
  3. python递归统计文件夹pdf文件数量

    2024-03-25 10:10:06       14 阅读
  4. 获取文件夹所有文件路径

    2024-03-25 10:10:06       39 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-25 10:10:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-25 10:10:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-25 10:10:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-25 10:10:06       18 阅读

热门阅读

  1. 手机IP地址如何更换

    2024-03-25 10:10:06       19 阅读
  2. 想注册滴滴司机驾龄不够怎么办?

    2024-03-25 10:10:06       14 阅读
  3. 测试缺陷定位的基本方法

    2024-03-25 10:10:06       18 阅读
  4. Spark—GraphX实战 ID Mapping

    2024-03-25 10:10:06       17 阅读
  5. 想注册滴滴司机驾龄不够怎么办?

    2024-03-25 10:10:06       16 阅读
  6. 10种常用排序算法简介

    2024-03-25 10:10:06       16 阅读
  7. 想注册滴滴司机驾龄不够怎么办?

    2024-03-25 10:10:06       17 阅读
  8. 【蓝桥杯3.23小白赛】(详解)

    2024-03-25 10:10:06       18 阅读
  9. 机器学习的步骤与方法

    2024-03-25 10:10:06       15 阅读
  10. 【ML】机器学习任务攻略 4

    2024-03-25 10:10:06       17 阅读