gpt4 book ai didi

java - 使用java搜索并打印文本文件

转载 作者:行者123 更新时间:2023-12-02 04:58:13 25 4
gpt4 key购买 nike

如何从 .t​​xt 文件中搜索文本并打印特定的文本行?例如我有一个名为 Airlines.txt 的 txt 文件,我搜索 MMHHHAAAA。然后,我想从“MMHHHAAAA:Malaysian Airlines”行中提取“Malaysian Airlines”

//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;
}

最佳答案

您可以在 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()

关于java - 使用java搜索并打印文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28552737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com