[英]Using Java Scanner class ,how do I get the most recent number which comes after specific String?
I have text log files which follow this format: 我有遵循以下格式的文本日志文件:
18:27:08.231 [main] DEBUG sample_client - This is a DEBUG message, line 39 Location 7 18:27:09.231 [main] DEBUG sample_client - This is anr DEBUG message, line 39 Location 17 18:27:10.231 [main] DEBUG sample_client - This is a DEBUG message, line 56 Location 23
18:27:08.231 [main] DEBUG sample_client-这是一条DEBUG消息,第39行7位置18:27:09.231 [main] DEBUG sample_client-这是an DEBUG消息,第39行,位置17 18:27:10.231 [main] DEBUG sample_client-这是一条DEBUG消息,第56行位置23
I would like to obtain the most recent integer, that comes after the String "Location" - here it is 23. 我想获取字符串“ Location”之后的最新整数-这里是23。
The following is my Scanner class so far : 以下是我到目前为止的Scanner类:
import org.apache.logging.log4j.flume; */
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;
import java.sql.Timestamp;
import java.util.Date;
import java.util.*;
import java.io.*;
import java.net.*;
public class ScannerTest { /* BEGINBRAC */
public static void main(String[] args) throws IOException {
int mostRecentLocation = 0;
Scanner scanner = new Scanner ("LogbackTutorialError.txt");
while (scanner.hasNextLine() ) {
final String lineFromFile = scanner.nextLine();
if(lineFromFile.contains("Location")){
System.out.print("the location is " + mostRecentLocation );
}
}
}
}// end class ScannerTest
How do I go about getting the most recent number after Location ? 如何获取位置信息后的最新号码?
You could do something with String.substring(int)
to remove everything from Location
on. 您可以使用
String.substring(int)
进行某些操作,以删除Location
上的所有内容。 Something like, 就像是,
if (lineFromFile.startsWith("Location")) {
int mostRecentLocation = Integer.parseInt(lineFromFile
.substring(1 + "Location".length()).trim());
System.out.println("the location is " + mostRecentLocation);
}
The following code shows how to create it. 以下代码显示了如何创建它。
import java.sql.Timestamp;
import java.util.Date;
import java.util.*;
import java.io.*;
import java.net.*;
public class ScannerTest {
public static void main(String[] args) throws FileNotFoundException {
int mostRecentLocation = 0;
File newFile = new File("LogbackTutorialError.log");
Scanner scanner = new Scanner (newFile);
int result = 0;
while (scanner.hasNextLine() ) {
String lineFromFile = scanner.nextLine();
Scanner lineScanner = new Scanner(lineFromFile);
if(lineScanner.findInLine("Location") != null){
result = lineScanner.nextInt() ;
mostRecentLocation = result;
}
}
System.out.println(" The location is : " + result );
}
}// end class ScannerTest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.