这是java程序,它将搜索特定文件夹中的字符串,即(文件夹中不包含任何文本文件)如果字符串在文件夹中,它提供了完美的输出但是如果该字符串在文本文件它没有给出任何输出我需要输出,好像在文件夹中搜索的字符串没有找到然后它将显示Nodata Found
public TextSearch() {
file = new File("C://Users//IBM_ADMIN//Desktop//EVERY WEEK LOGS\\B");
scanner = new Scanner(System.in);
System.out.println("Enter a word");
word = scanner.nextLine();
File[] listOfFiles = file.listFiles();
startSearch(listOfFiles);
Iterator<String> iterator = counter.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println(key + " contain this word " + word + " " + counter.get(key) + "times");
}
}
public void startSearch(File[] list) {
for (int i = 0; i < list.length; i++) {
if (list[i].isFile()) {
try {
reader = new FileReader(list[i]);
buffReader = new BufferedReader(reader);
String line = "";
while ((line = buffReader.readLine()) != null) {
if (line.contains(word)) {
if (counter.containsKey(list[i].getName())) {
Integer count = counter.get(list[i].getName());
count++;
counter.put(list[i].getName(), count);
} else {
counter.put(list[i].getName(), 1);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
new TextSearch();
}}
答案 0 :(得分:0)
试试这个:
诀窍是将文件名的计数器设为0:counter.put(list[i].getName(), 0);
public TextSearch() {
file = new File("C://Users//IBM_ADMIN//Desktop//EVERY WEEK LOGS\\B");
file2 = new File("C://Users//IBM_ADMIN//Desktop//EVERY WEEK LOGS\\C");
scanner = new Scanner(System.in);
System.out.println("Enter a word");
word = scanner.nextLine();
startSearch(file, file2);
Iterator<String> iterator = counter.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
if (counter.get(key) == 0) {
System.out.println(key + " does not contain word " + word);
} else {
System.out.println(key + " contain this word " + word + " " + counter.get(key) + "times");
}
}
}
public void startSearch(File... list) {
for (File file : list) {
File[] listOfFiles = file.listFiles();
innerStartSearch(listOfFiles);
}
}
public void innerStartSearch(File[] list) {
for (int i = 0; i < list.length; i++) {
if (list[i].isFile()) {
counter.put(list[i].getName(), 0);
try {
reader = new FileReader(list[i]);
buffReader = new BufferedReader(reader);
String line = "";
while ((line = buffReader.readLine()) != null) {
if (line.contains(word)) {
Integer count = counter.get(list[i].getName());
count++;
counter.put(list[i].getName(), count);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}