[英]Find a string (or a line) in a txt File Java
假設我有一個包含以下內容的txt文件:
john
dani
zack
用戶將輸入一個字符串,例如“omar”我希望程序搜索該字符串“omar”的txt文件,如果它不存在,只需顯示“不存在”。
我嘗試了函數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
}
}
使用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
是用戶搜索的字符串
UPDATE
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
執行此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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.