Java上机实现统计某一目录下每个文件中出现的字母个数、数字个数、空格个数及行数?
package pers.ascend.kukii.core.interview.other.计算字符个数;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 说明:
*
* @author ascend
* 2020/10/23 14:28
*/
public class Client {
public static void main(String[] args) throws IOException {
String packagePath = "pers.ascend.kukii.core.interview.other.计算字符个数";
String basePath = Objects.requireNonNull(Client.class.getClassLoader().getResource("")).getPath();
String path = basePath.substring(1).replace("target/classes", "src/main/java") + "/" + packagePath.replace('.', '/');
List<File> files = listFile(path);
files.forEach(file -> System.out.println(file.getName()));
Pattern charP = Pattern.compile("[a-zA-Z]");
AtomicInteger charCount = new AtomicInteger();
Pattern numberP = Pattern.compile("\\d");
AtomicInteger numberCount = new AtomicInteger();
Pattern spaceP = Pattern.compile(" ");
AtomicInteger spaceCount = new AtomicInteger();
files.forEach(file -> {
try {
String input = Files.readString(file.toPath());
Matcher charM = charP.matcher(input);
while (charM.find()) {
charCount.getAndIncrement();
}
Matcher numberM = numberP.matcher(input);
while (numberM.find()) {
numberCount.getAndIncrement();
}
Matcher spaceM = spaceP.matcher(input);
while (spaceM.find()) {
spaceCount.getAndIncrement();
}
} catch (IOException e) {
e.printStackTrace();
}
});
System.out.println("charCount.get() = " + charCount.get());
System.out.println("numberCount.get() = " + numberCount.get());
System.out.println("spaceCount.get() = " + spaceCount.get());
}
private static List<File> listFile(String path) throws IOException {
List<File> retList = new ArrayList<>();
Files.list(Paths.get(path)).forEach(path1 -> {
if (path1.toFile().isDirectory()) {
try {
retList.addAll(listFile(path1.toString()));
} catch (IOException e) {
e.printStackTrace();
}
} else {
retList.add(path1.toFile());
}
});
return retList;
}
}
看这里,看这里
文章总目录:博客导航
参考文章:https://blog.youkuaiyun.com/u_ascend/article/details/109244454