【发布时间】:2013-12-23 11:23:55
【问题描述】:
假设我有一个 txt 文件,其中包含:
john
dani
zack
用户将输入一个字符串,例如“omar” 我希望程序在该 txt 文件中搜索字符串“omar”,如果它不存在,只需显示“不存在”。
我尝试了函数String.endsWith()或String.startsWith(),但那当然显示“不存在”3次。
我在 3 周前才开始使用 Java,所以我是个新手……请多多包涵。 谢谢。
【问题讨论】:
假设我有一个 txt 文件,其中包含:
john
dani
zack
用户将输入一个字符串,例如“omar” 我希望程序在该 txt 文件中搜索字符串“omar”,如果它不存在,只需显示“不存在”。
我尝试了函数String.endsWith()或String.startsWith(),但那当然显示“不存在”3次。
我在 3 周前才开始使用 Java,所以我是个新手……请多多包涵。 谢谢。
【问题讨论】:
只需阅读此文本文件并将每个单词放入List,您就可以检查List 是否包含您的单词。
你可以使用Scanner scanner=new Scanner("FileNameWithPath");来读取文件,你可以尝试关注给List添加文字。
List<String> list=new ArrayList<>();
while(scanner.hasNextLine()){
list.add(scanner.nextLine());
}
然后检查你的话是否存在
if(list.contains("yourWord")){
// found.
}else{
// not found
}
顺便说一句,您也可以直接在文件中搜索。
while(scanner.hasNextLine()){
if("yourWord".equals(scanner.nextLine().trim())){
// found
break;
}else{
// not found
}
}
【讨论】:
break
使用String.contains(your search String) 代替String.endsWith() 或String.startsWith()
例如
str.contains("omar");
【讨论】:
你可以换一种方式。 在遍历文件并中断时,如果找到匹配项,则打印“存在”而不是打印“不存在”;如果遍历整个文件但没有找到匹配项,则继续并显示“不存在”。
另外,使用String.contains() 代替str.startsWith() 或str.endsWith()。包含检查将在整个字符串中搜索匹配项,而不仅仅是在开头或结尾处。
希望它有意义。
【讨论】:
读取文本文件内容:http://www.javapractices.com/topic/TopicAction.do?Id=42
然后使用textData.contains(user_input);方法,其中textData是从文件中读取的数据,user_input是用户搜索的字符串
更新
public static StringBuilder readFile(String path)
{
// Assumes that a file article.rss is available on the SD card
File file = new File(path);
StringBuilder builder = new StringBuilder();
if (!file.exists()) {
throw new RuntimeException("File not found");
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return builder;
}
此方法返回根据您从作为参数给出的文本文件中读取的数据创建的 StringBuilder。
您可以像这样查看用户输入的字符串是否在文件中:
int index = readFile(filePath).indexOf(user_input);
if ( index > -1 )
System.out.println("exists");
【讨论】:
您可以使用Files.lines:
try(Stream<String> lines = Files.lines(Paths.get("...")) ) {
if(lines.anyMatch("omar"::equals)) {
//or lines.anyMatch(l -> l.contains("omar"))
System.out.println("found");
} else {
System.out.println("not found");
}
}
请注意,它使用 UTF-8 字符集来读取文件,如果这不是您想要的,您可以将您的字符集作为第二个参数传递给 Files.lines。
【讨论】: