以下是一个针对该需求的Java程序,其中包括了工具类、接口和主程序,以及在配置文件application.properties中配置文件路径地址和要查找的字符串。请注意,为了方便,以下代码均没有做过多的数据校验。
### 工具类
```java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class StringUtils {
public static int countSubstring(File file, String substr) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
int count = 0;
while ((line = reader.readLine()) != null) {
count += countOccurencesOfSubstring(line, substr);
}
return count;
}
private static int countOccurencesOfSubstring(String str, String substr) {
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = str.indexOf(substr, lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += substr.length();
}
}
return count;
}
}
```
### 接口
```java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Properties;
public class TextFileAnalyzer {
private String folderPath;
private String targetSubstring;
private int maxCount;
private String maxFile;
public TextFileAnalyzer(Properties props) {
this.folderPath = props.getProperty("folderPath");
this.targetSubstring = props.getProperty("targetSubstring");
}
public void analyze() {
File folder = new File(folderPath);
if (!folder.exists()) {
System.out.println("指定的文件夹不存在!");
return;
}
File[] files = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".txt"));
Arrays.sort(files, Comparator.comparing(File::getName));
for (File file : files) {
try {
int count = StringUtils.countSubstring(file, targetSubstring);
System.out.println(file.getName() + ": " + count + " 个字符串");
if (count > maxCount) {
maxCount = count;
maxFile = file.getName();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (maxFile != null) {
System.out.println("字符串个数最多的文件是:" + maxFile + ",共有 " + maxCount + " 个字符串。");
} else {
System.out.println("没有找到任何符合条件的文本文件!");
}
}
}
```
### 主程序
```java
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties props = new Properties();
try (InputStream is = Main.class.getClassLoader().getResourceAsStream("application.properties")) {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
}
TextFileAnalyzer analyzer = new TextFileAnalyzer(props);
analyzer.analyze();
}
}
```
### 配置文件`application.properties`
```properties
folderPath = 文件夹路径
targetSubstring = 要查找的字符串
```
需要将`folderPath`改为指定文件夹的路径,`targetSubstring`改为要查找的字符串。完整程序需要引入Java主流的配置文件解析工具,如Apache Commons Configuration等,这里为了简化代码,直接使用了Java标准库提供的`Properties`类。