我正在尝试创建一个允许您在文本文件中搜索单词的小程序,然后程序应该打印出文本所在的整行。
示例:
test.txt
don't mind this text
don't mind this either
然后当你让程序搜索单词“text”时,它应该打印出“不要介意这个文字”。
最好的方法是什么?
这就是我所拥有的;
public boolean findFileInCache(){
try (BufferedReader br = new BufferedReader(new FileReader("direct.txt")))
{
while ((name = br.readLine()) != null)
{
Process p = Runtime.getRuntime().exec(name);
}
}
catch (IOException e1) { }
return true;
}
答案 0 :(得分:3)
使用BufferedReader
使用BufferedReader.readLine()
方法逐行读取文件。
对于每一行,使用正则表达式检查单词是否在其中,或者将行拆分为String[]
(使用String.split()
),并迭代结果数组中的条目以检查如果它们中的任何一个是所需的单词。如果有所需的单词 - 打印整行。
如果您选择了第二个建议,请不要忘记使用equals()
检查两个字符串的相等性,而不是使用==
答案 1 :(得分:2)
您需要做几件事:
您已经找到了解决方案的两个核心部分:
BufferedReader.readLine()
while
循环中进行的,因此您一次只能处理一行现在,你需要弄清楚如何处理每一行。虽然您没有包含类型,但name
是一个字符串。它会更好:
while ((String name = br.readLine()) != null) {
... do something with `line`
}
如果您的代码编译时没有String
,则表示您将name
声明为全局代码。不要这样做,直到你知道你在做什么。
将事物分解为方法是好的;所以让我们“用line
做点什么”现在使用一种方法:
while ((String name = br.readLine()) != null) {
if(matches(line,"text")) {
System.out.println(line);
}
}
现在你需要写matches()
:
private boolean matches(String line, String word) {
boolean result = // work out whether it's a match
return result;
}
那么,你如何写出matches()
的内容?
那么,首先看一下String
中可用的方法。它有contains()
和split()
等方法。其中一些方法返回其他类型,如数组。您的教学材料和参考资料将告诉您如何查看阵列。答案就在那里。