简体   繁体   中英

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

I would like to obtain the most recent integer, that comes after the String "Location" - here it is 23.

The following is my Scanner class so far :

 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM