在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 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 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