在txt File Java中查找字符串(或行) [英] Find a string (or a line) in a txt File Java

查看:125
本文介绍了在txt File Java中查找字符串(或行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含以下内容的txt文件:

let's say I have a txt file containing:

john
dani
zack

用户将输入一个字符串,例如omar
我希望程序搜索该文本字符串omar的文件,如果它不存在,只显示不存在。

the user will input a string, for example "omar" I want the program to search that txt file for the String "omar", if it doesn't exist, simply display "doesn't exist".

我尝试了函数String.endsWith()或String .startsWith(),但当然显示不存在3次。

I tried the function String.endsWith() or String.startsWith(), but that of course displays "doesn't exist" 3 times.

我在3周前开始使用java,所以我是一个新手... 。请多多包涵。
谢谢。

I started java only 3 weeks ago, so I am a total newbie...please bear with me. thank you.

推荐答案

只需阅读此文本文件并将每个单词放入列出,您可以检查列表是否包含您的单词。

Just read this text file and put each word in to a List and you can check whether that List contains your word.

您可以使用扫描仪扫描程序=新扫描程序(FileNameWithPath); 来读取文件,您可以尝试以下操作添加单词到列表

You can use Scanner scanner=new Scanner("FileNameWithPath"); to read file and you can try following to add words to List.

 List<String> list=new ArrayList<>();
 while(scanner.hasNextLine()){
     list.add(scanner.nextLine()); 

 }

然后检查你的话是否存在

Then check your word is there or not

if(list.contains("yourWord")){

  // found.
}else{
 // not found
}

BTW你也可以直接在文件中搜索。

BTW you can search directly in file too.

while(scanner.hasNextLine()){
     if("yourWord".equals(scanner.nextLine().trim())){
        // found
        break;
      }else{
       // not found

      }

 }

这篇关于在txt File Java中查找字符串(或行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆