gpt4 book ai didi

java - 搜索文件的内容

转载 作者:行者123 更新时间:2023-11-30 04:16:48 24 4
gpt4 key购买 nike

我没有太多处理文件的经验。我有一个文件。我已将以下内容写入文件

Test 112
help 456
news 456
Friendly 554

fileOUT.write("Test 112\r\n");//this is a example of how I entered the data.

现在,我尝试在文件中搜索单词 news,并显示该行中包含单词 news 的所有内容。

这是我尝试过的。

if(fileIN.next().contains("news")){
System.out.println("kkk");
}

这不起作用。下面确实找到了一个单词新闻,因为它显示了 KKK,但我不知道如何只显示找到它的新闻行。

while(fileIN.hasNext()){
if(fileIN.next().contains("Play")){
System.out.println("kkk");

}
}

必须显示的是news 456。谢谢您

最佳答案

您想要调用fileIN.nextLine().contains("news")

尝试使用Scanner如果你还没有类的话。它在通过某个轮廓符(在本例中为新行字符)从流中分割输入方面做得非常出色。

这是一个简单的代码示例:

String pathToFile = "data.txt";
String textToSearchFor = "news";
Scanner scanner = new Scanner(pathToFile);
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains(textToSearchFor)){
System.out.println(line);
}
}
scanner.close();

这是一个高级代码示例,它的作用比您要求的要多得多。享受吧!

//Search file for an array of strings. Ignores case if caseSensitive is false.
public void searchFile(String file, boolean caseSensitive, String...textToSearchFor){
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine()){
String originalLine = scanner.nextLine();
String line = originalLine;
if(!caseSensitive) line = line.toLowerCase();
for(String searchText : textToSearchFor){
if(!caseSensitive) searchText = searchText.toLowerCase();
if(line.contains(searchText)){
System.out.println(originalLine);
break;
}
}
}
scanner.close();
}

//usage
searchFile("data.txt",true,"news","Test","bob");
searchFile("data.txt",true,new String[]{"test","News"});

关于java - 搜索文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166341/

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