在Java中搜索文本文件

4

我正在尝试搜索一个文本文件,如果找到用户输入的内容,就返回整个句子(包括空格)。但显然我只得到了第一个字符串,而且在句子中没有其他内容。例如,如果我有一个名为"data.txt"的文本文件,第一行的内容是"我是传奇"。当用户输入"I am a legend"后,搜索文件后的输出是"I"。任何帮助都将不胜感激。

 public static void Findstr() { // This function searches the text for the    string

    File file = new File("data.txt");

     Scanner kb = new Scanner(System.in);

    System.out.println(" enter the content you looking for");
    String name = kb.next();
    Scanner scanner;
    try {
        scanner = new Scanner(file).useDelimiter( ",");

        while (scanner.hasNext()) {
            final String lineFromFile = scanner.nextLine();
            if (lineFromFile.contains(name)) {
                // a match!
                System.out.println("I found " + name);
                break;
            }
        }
    } catch (IOException e) {
        System.out.println(" cannot write to file " + file.toString());
    }

最好从"data.text"文件中提取几行。 - Shirishkumar Bari
没关系,我找到问题了。问题出在 kb.next() 上。应该改为 kb.nextLine()。 - user4766730
3个回答

7
package com.example;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileSearch {

    public void parseFile(String fileName,String searchStr) throws FileNotFoundException{
        Scanner scan = new Scanner(new File(fileName));
        while(scan.hasNext()){
            String line = scan.nextLine().toLowerCase().toString();
            if(line.contains(searchStr)){
                System.out.println(line);
            }
        }
    }


    public static void main(String[] args) throws FileNotFoundException{
        FileSearch fileSearch = new FileSearch();
        fileSearch.parseFile("src/main/resources/test.txt", "am");
    }

}


test.txt contains:
I am a legend
Hello World
I am Ironman

Output:
i am a legend
i am ironman

上述代码执行不区分大小写的搜索。您应该使用nextLine()获取完整行。next()根据空格符分割单词。

Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next()


我该如何使用Scanner解析文件,而不是使用字符串()“am”? - user4766730
1
在上面的例子中,am是搜索字符串。您可以将其替换为任何您想要的内容。您还可以要求用户为您输入一个字符串,并将其作为参数传递给该方法。 - takeradi
我将Scanner作为参数包含在内,但它就是不起作用。 public static void parseFile(String fileName, Scanner searchStr) throws FileNotFoundException { Scanner scan = new Scanner(new File(fileName)); while(scan.hasNext()){ String line = scan.nextLine().toLowerCase().toString(); if(line.contains(searchStr)){ System.out.println(line); } } } - user4766730
函数parseFile的参数是两个字符串对象。你不能将Scanner传递给它。如果你想要传递Scanner,你需要改变方法的定义为:public void parseFile(String fileName,String searchStr, Scanner scanner) throws FileNotFoundException - takeradi
我正在尝试获取用户输入,然后将该输入传递到parsefile方法中。这可能吗? - user4766730
显示剩余2条评论

0

当你正在扫描输入时...

Scanner kb = new Scanner(System.in);
System.out.println(" enter the content you looking for");
String name = kb.next();

您只接受一个令牌。您应该使用kb.nextLine()接受整行作为要搜索的令牌。


0

Scanner.next(); 返回下一个字符,而不是使用Scanner.readLine();

编辑: 相信 Scanners 使用 .nextLine(); 而不是 .readLine();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接