Java-在文本文件中搜索字符串,然后打印行 [英] Java- Searching for a string in text file, then print line
本文介绍了Java-在文本文件中搜索字符串,然后打印行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个代码,用户可以在该代码中搜索文本文件中的特定字符串(不区分大小写),并打印找到该字符串的整行.我的代码段在这里:
I am writing a code where the user can search a text file for a particular string, (case insensitive) and it prints the entire line where the string is found. My code snippet is here:
public static void search() throws FileNotFoundException
{
Scanner input = new Scanner( System.in );
int fieldNumber = 0;
if ( fieldNumber == 0 )
{
System.out.println("Enter field value to search for: ");
String fieldValue = input.next();
if ("orange".equalsIgnoreCase(fieldValue))
{
// Here is where I am stuck.
{
}
推荐答案
try
{
Scanner file = new Scanner(new File("file.txt"));
String str = str.nextLine();
System.out.print("Enter search ");
Num = input.nextInt();
if ( Num == 0 )
{
System.out.println("Enter search for: ");
String Value = input.next();
while (file.hasNextLine())
{
final String lineFromFile = file.nextLine();
if(lineFromFile.contains(Value))
{
System.out.println("file.txt");
System.out.println(lineFromFile);
break;
}
这篇关于Java-在文本文件中搜索字符串,然后打印行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文