使用java搜索和打印文本文件

时间:2015-02-17 00:26:54

标签: java search text printing

如何搜索文本并从.txt文件中打印出特定的文本行? 例如我有一个名为airlines.txt的txt文件,我搜索MMHHHAAAA。然后,我想从“MMHHHAAAA:马来西亚航空公司”这一行中提取“马来西亚航空公司”

//Scan file airlines.txt
Scanner scanner = new Scanner(new File("airlines.txt"));
while(scanner.hasNextLine()){
//Will this work?
  String s = scan.nextLine();
  Scanner line = new Scanner(s);
  String airline;
//How do i continue from here to scan for MMHHHAAAA and then print out the following line of text
}
System.out.println("Airline is" + airline);
return airline;
}

3 个答案:

答案 0 :(得分:2)

您可以在Java 8中使用它:

final Path path = Paths.get("airlines.txt");

final Optional<String> theLine;

try (
    final Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)
) {
    theLine = lines.filter(s -> s.startsWith("MMHHHAAAA:"))
        .findFirst();
}

if (theLine.isPresent())
    // do something with theLine.get()

答案 1 :(得分:0)

您可以使用String.indexOf("")方法。

if (s.indexOf("your-search-string") != -1) {
   //matched the pattern
   System.out.println(s);
}

您可以使用substring():之后提取部件。 System.out.println(s.substring(":"));

详细了解Java strings及其方法。

答案 2 :(得分:0)

一种可能性......

    Scanner scanner = new Scanner(new File("airlines.txt"));
    while(scanner.hasNextLine()){

      String currentLine = scanner.nextLine();
      if(currentLine.indexOf("MMHHHAAAA") != -1){
          String airline = currentLine.split(":")[1];
          System.out.println("Airline is " + airline);
      }
    }