以下是一个简单的Java程序,实现了对指定文件夹下的所有文本文件进行字符串数统计,并输出其中字符串数最多的文件的文件名和字符串数。
工具类:
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
// 用于读取文本文件并返回其中字符串个数
public class TextFileReader {
public static int getCount(String filename) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
int count = 0;
String line;
while ((line = reader.readLine()) != null) {
count += line.trim().split("\\s+").length;
}
reader.close();
return count;
}
}
```
接口:
```java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
// 用于遍历文件夹并输出其中字符串数最多的文件的文件名和字符串数
public class TextFileCounter {
public static void countFiles(String folderPath) throws IOException {
File folder = new File(folderPath);
File[] files = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));
Arrays.sort(files, Comparator.comparing(File::getName));
String maxFile = null;
int maxCount = 0;
for (File file : files) {
int count = TextFileReader.getCount(file.getAbsolutePath());
System.out.println(file.getName() + ": " + count + "个字符串");
if (count > maxCount) {
maxCount = count;
maxFile = file.getName();
}
}
if (maxFile != null) {
System.out.println("字符串数最多的文件是:" + maxFile + ",共有" + maxCount + "个字符串。");
} else {
System.out.println("没有找到任何文本文件!");
}
}
}
```
主程序:
```java
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
TextFileCounter.countFiles("文件夹的路径");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意需要将 "文件夹的路径" 替换为实际的目标文件夹路径。