【问题标题】:Find a string (or a line) in a txt File Java在 txt 文件 Java 中查找字符串(或行)
【发布时间】:2013-12-23 11:23:55
【问题描述】:

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

john
dani
zack

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

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

我在 3 周前才开始使用 Java,所以我是个新手……请多多包涵。 谢谢。

【问题讨论】:

    标签: java string file


    【解决方案1】:

    只需阅读此文本文件并将每个单词放入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
    
          }
    
     }
    

    【讨论】:

    • 为什么把它放到一个列表中,而不是直接检查该行并在找到匹配项时打破循环?像这样,每次你读入整个文件,我们不知道它的大小。可能效率很低....
    • @EdgarBoda 你的想法也在那里
    • 最后一个方法,我可以直接在文件内部搜索,找到行时如何打破循环?它正在显示:未找到 4 次,然后找到,然后直到文件末尾才找到
    • @user3040333 放一个break
    • @Ruchira 已经尝试过了,它以某种方式取消了 if 语句,所以它现在显示 not found 不管字符串是否存在
    【解决方案2】:

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

    例如

     str.contains("omar"); 
    

    【讨论】:

      【解决方案3】:

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

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

      希望它有意义。

      【讨论】:

        【解决方案4】:

        读取文本文件内容: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");
        

        【讨论】:

        • 而不是textData,我应该输入文件名吗?例如 File file = new File();然后放“文件”而不是 textData ?
        【解决方案5】:

        您可以使用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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-16
          • 2018-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-03-14
          相关资源
          最近更新 更多