package read;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class TextFileReader {
public static Map<String, Integer> countWords(String folderPath, String[] searchStrings) throws IOException {
File folder = new File(folderPath);
File[] files = folder.listFiles();
Map<String, Integer> counts = new HashMap<>();
for (File file : files) {
if (file.getName().endsWith(".txt")) {
try(BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while((line = reader.readLine()) != null) {
for (String searchString : searchStrings) {
int count = counts.getOrDefault(searchString, 0);
count += countOccurrences(line, searchString);
counts.put(searchString, count);
}
}
}
}
}
return counts;
}
private static int countOccurrences(String text, String searchString) {
int count = 0;
int index = text.indexOf(searchString);
while (index != -1) {
count++;
index = text.indexOf(searchString, index + 1);
}
return count;
}
}
package read;
import java.io.IOException;
import java.util.Map;
public class LocalTextFileManager implements TextFileManager {
private final String folderPath;
public LocalTextFileManager(String folderPath) {
this.folderPath = folderPath;
}
@Override
public Map<String, Integer> countWords(String[] searchStrings) throws IOException {
return TextFileReader.countWords(folderPath, searchStrings);
}
}
package read;
import java.io.IOException;
import java.util.Map;
public interface TextFileManager {
Map<String, Integer> countWords(String[] searchStrings) throws IOException;
}
package read;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
public class Application {
public static void main(String[] args) {
try {
Properties properties = new Properties();
FileInputStream inputStream = new FileInputStream("application.properties");
properties.load(inputStream);
String folderPath = properties.getProperty("folder.path");
String[] searchStrings = properties.getProperty("search.strings").split(",");
if(searchStrings!=null&&!"".equals(searchStrings)) {}
TextFileManager textFileManager = new LocalTextFileManager(folderPath);
Map<String, Integer> counts = textFileManager.countWords(searchStrings);
System.out.println("Result for folder " + folderPath);
int maxCount = Integer.MIN_VALUE;
String maxString = "";
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
if (entry.getValue() > maxCount) {
maxCount = entry.getValue();
maxString = entry.getKey();
}
}
System.out.println("出现最多的字符是:" + maxString + " \n次数为: " + maxCount);
} catch (FileNotFoundException e) {
System.err.println("没有读取到文件夹");
} catch (IOException e) {
e.printStackTrace();
}
}
}