【发布时间】:2021-04-12 13:18:50
【问题描述】:
在我的代码中,我可以列出我电脑上文件夹中的所有文件,但要检查关键字是否存在于我在 StringBuffer 中使用 indexOf() 的那些文件中。我面临的问题是没有打印出具有该关键字的文件名的所需输出。 我无法找到错误在哪里或我犯了什么错误。
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ListOfFiles {
public static void main(String args[]) throws IOException {
// Creating a File object for directory
File directoryPath = new File("C:\\Users\\nanis\\Downloads\\New folder");
// List of all files and directories
File filesList[] = directoryPath.listFiles();
// System.out.println("List of files and directories in the specified directory:");
Scanner sc = null;
for (File file: filesList) {
// System.out.println("File name: "+file.getName());
// System.out.println("File path: "+file.getAbsolutePath());
// System.out.println("Size :"+file.getTotalSpace());
// Instantiating the Scanner class
sc = new Scanner(file);
String input;
StringBuffer sb = new StringBuffer();
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input + " ");
int integer = sb.indexOf("VM"); // the keyword is "VM" that I want to search
if (integer > 0) {
System.out.println("keyword is present in " + file.getAbsolutePath())
}
}
}
}
}
【问题讨论】:
-
将所有行附加到
StringBuffer并重复在整个缓冲区中搜索关键字是没有意义的。只需在阅读后立即搜索特定行 (input)。此外,关键字可能位于行首,因此您应该使用>= 0作为索引。或者首先使用if(input.contains("VM")) …。你应该在try(…)语句中使用扫描器。