我想要在文本文件
中最后一次出现特定字符串的行
Scanner file = new Scanner(new File("C:\\Users\\prudra\\Desktop\\Axalta\\20180406114505\\activemq.log_app1"));
int i = 0;
String str = file.nextLine();
System.out.print("Enter search ");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the environment you want to execute the script (Dev/QA/Prod)");
String name = sc.nextLine();
while (file.hasNextLine()) {
final String lineFromFile = file.nextLine();
i++;
if (lineFromFile.contains(name)) {
//System.out.println("file.txt");
}
}
System.out.println(i);
}
答案 0 :(得分:0)
如果我理解正确你想要这样的东西吗?
int lastIndex= 0;
//start of loop
if (lineFromFile.contains(name)) {
lastIndex = i;
}
//end of loop
if (lastIndex != 0) {
System.out.println(lastIndex);
} else {
System.out.println("Line not found");
}
或者只是在条件中递增i
int i = 0;
//start of loop
if (lineFromFile.contains(name)) {
i++;
}
//end of loop
if (i != 0) {
System.out.println(i + 1); //because you start i from 0
} else {
System.out.println("Line not found");
}
答案 1 :(得分:0)
Scanner file = new Scanner(new File("C:\\Users\\prudra\\Desktop\\Axalta\\20180406114505\\activemq.log_app1"));
int i = 0;
int index = 0;
String str = file.nextLine();
System.out.print("Enter search ");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the environment you want to execute the script (Dev/QA/Prod)");
String name = sc.nextLine();
while (file.hasNextLine()) {
final String lineFromFile = file.nextLine();
i++;
if (lineFromFile.contains(name)) {
//saves index of occurance
index = i;
}
}
System.out.println(index);
}
我想这就是你要找的东西。只需要一个变量来保存最后一次出现的行。由于你只想要最后一行,所以读完所有行index
将保留最后一行。如果你想要第一个,你可以在找到第一个后返回i
。如果你需要x出现,你需要在另一个变量中保持计数。
编辑:不确定行是否表示行文本的行号,如果是文本,而不是使用索引来保存行号,则可以使用字符串来保存行文本,如lineText = lineFromFile;
答案 2 :(得分:0)
将最后一行存储在局部变量中并在循环外访问它。
示例:
Scanner file = new Scanner(new File("C:\\Users\\prudra\\Desktop\\Axalta\\20180406114505\\activemq.log_app1"));
int i = 0;
String str = file.nextLine();
System.out.print("Enter search ");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the environment you want to execute the script (Dev/QA/Prod)");
String name = sc.nextLine();
String lastLine="";
int lastLineNumber=-1;
while (file.hasNextLine()) {
final String lineFromFile = file.nextLine();
i++;
if (lineFromFile.contains(name)) {
lastLine=lineFromFile;
lastLineNumber=i;
//System.out.println("file.txt");
}
}
System.out.println(i);
System.out.println("Last Line: "+lastLine);
System.out.println("Last Line Number: "+lastLineNumber);
}
只要文件指针从第一行开始读取到文件的最后一行,这实际上就有效。因为在循环结束时,您将存储所需文本行的最后一次出现,然后您可以稍后访问它。