java根据第一个单词在文件中查找特定行

时间:2015-11-19 21:44:15

标签: java

我有一个我要导入的文件,我想要做的是询问用户的输入并将其用作查找正确行的基础。我把它设置成这样:

     public class ReadLines {
    public static void main(String[] args) throws FileNotFoundException
    {
         File fileNames = new File("file.txt");
     Scanner scnr = new Scanner(fileNames);
     Scanner in = new Scanner(System.in);

    int count = 0;
    int lineNumber = 1;

    System.out.print("Please enter a name to look up: ");
    String newName = in.next();

    while(scnr.hasNextLine()){
          if(scnr.equals(newName))
          {
              String line = scnr.nextLine();
              System.out.print(line);
          }
      } 
}

现在,我只是想让它打印出来,看看我已经捕获了它,但那不起作用。有没有人有任何想法?此外,如果重要,我不能使用try和catch或数组。 非常感谢!

2 个答案:

答案 0 :(得分:1)

您需要在本地变量中缓存该行,以便稍后将其打印出来。这样的事情可以解决问题:

var book = {
    year: 2004,
    edition:1,
    get newYear(){
        return "Hello, it's " + this.year;
    },
    set newYear(y, e){
        this.year = y;
        this.edition = e;
    }
};

希望这有帮助!

答案 1 :(得分:0)

我做了以下几行:

Scanner in = new Scanner(System.in);

System.out.print("Please enter a name to look up: ");
String name = in.next();

List<String> lines = Files.readAllLineS(new File("file.txt").toPath(), StandardCharsets.UTF_8);
Optional<String> firstResult = lines.stream().filter(s -> s.startsWith(name)).findFirst();

if (firstResult.isPresent) {
    System.out.print("Line: " + firstResult.get());
} else {
    System.out.print("Nothing found");
}