本文主要是介绍统计文件夹下所有文件的字数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
统计文件夹下所有.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 directoryFiles.walkFileTree(startPath, new SimpleFileVisitor<Path>() {@Overridepublic 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;}@Overridepublic 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);}
}
这篇关于统计文件夹下所有文件的字数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!