在 txt 文件 Java 中查找字符串(或一行)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20418319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:48:27  来源:igfitidea点击:

Find a string (or a line) in a txt File Java

javastringfile

提问by user3040333

let's say I have a txt file containing:

假设我有一个 txt 文件,其中包含:

john
dani
zack

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".

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

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

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

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

我在 3 周前才开始使用 Java,所以我是一个新手......请耐心等待。谢谢你。

采纳答案by Ruchira Gayan Ranaweera

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

只需阅读此文本文件并将每个单词放入 a 中List,您就可以检查其中是否List包含您的单词。

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

您可以使用Scanner scanner=new Scanner("FileNameWithPath");读取文件,您可以尝试按照以下步骤将单词添加到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 you can search directly in file too.

顺便说一句,您也可以直接在文件中搜索。

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

      }

 }

回答by Prabhakaran Ramaswamy

use String.contains(your search String)instead of String.endsWith()or String.startsWith()

使用 String.contains(your search String)代替String.endsWith()String.startsWith()

eg

例如

 str.contains("omar"); 

回答by Ankur Shanbhag

You can go other way around. Instead of printing 'does not exist', print 'exists' if match is foundwhile traversing the file and break; If entire file is traversed and no match was found, only then go ahead and display 'does not exist'.

你可以换个方式。如果在遍历文件并中断时找到匹配项,则不打印“不存在”,而是打印“存在”;如果遍历整个文件并且没有找到匹配项,则只有这样才能继续并显示“不存在”。

Also, use String.contains()in place of str.startsWith()or str.endsWith(). Contains check will search for a match in the entire string and not just at the start or end.

此外,使用或String.contains()代替。包含检查将在整个字符串中搜索匹配项,而不仅仅是在开头或结尾。str.startsWith()str.endsWith()

Hope it makes sense.

希望这是有道理的。

回答by Hitman

Read the content of the text file: http://www.javapractices.com/topic/TopicAction.do?Id=42

阅读文本文件的内容:http: //www.javapractices.com/topic/TopicAction.do?Id=42

And after that just use the textData.contains(user_input);method, where textDatais the data read from the file, and the user_inputis the string that is searched by the user

之后只需使用该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;
    }

This method returns the StringBuilder created from the data you have read from the text file given as parameter.

此方法返回根据您从作为参数给出的文本文件中读取的数据创建的 StringBuilder。

You can see if the user input string is in the file like this:

您可以像这样查看用户输入字符串是否在文件中:

int index = readFile(filePath).indexOf(user_input);
        if ( index > -1 )
            System.out.println("exists");

回答by Alex

You can do this with 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");
    }
}

Note that it uses the UTF-8 charset to read the file, if that's not what you want you can pass your charset as the second argument to Files.lines.

请注意,它使用 UTF-8 字符集来读取文件,如果这不是您想要的,您可以将您的字符集作为第二个参数传递给Files.lines.