在文本File Java中查找字符串(或行)

时间:2013-12-06 07:21:11

标签: java string file

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

john
dani
zack

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

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

我3周前才开始使用java,所以我是新手...请耐心等待我。 谢谢。

5 个答案:

答案 0 :(得分:4)

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

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

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

      }

 }

答案 1 :(得分:1)

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

例如

 str.contains("omar"); 

答案 2 :(得分:1)

你可以走另一条路。 在遍历文件并中断时,如果找不到匹配,则打印“存在”;而不是打印“不存在”;如果遍历整个文件并且未找到匹配项,则仅继续显示“不存在”。

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

希望它有意义。

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

相关问题