简体   繁体   中英

Java search in a text and returning multiple lines around it

I am searching in a bigger txt file (~8Mb) where every row looks like this: dd/mm/yyyy hh:mm:ss after these there are different identifiers and after that a value.

dd/mm/yyyy  hh:mm:ss identifier not relevant in search
dd/mm/yyyy  hh:mm:ss identifier not relevant in search
dd/mm/yyyy  hh:mm:ss identifier not relevant in search
dd/mm/yyyy  hh:mm:ss identifier value -> value that I am searching for
dd/mm/yyyy  hh:mm:ss identifier not relevant in search
dd/mm/yyyy  hh:mm:ss identifier not relevant in search

I have successfully found and print out the whole line which contains the value that I am searching for, but I need to print the values around it(9 line after, 5 lines before), in the other lines.

    public void fajl(String fajlnev, String szeriaszam) throws FileNotFoundException{
    int sorszam = 0;
    Scanner serialnummer = new Scanner(new File(fajlnev));
    while(serialnummer.hasNext()){ //keresés pörgetése
        String line = serialnummer.nextLine().toString();
        sorszam++;
        if(line.contains(szeriaszam)){
            System.out.println(line + "\n" + sorszam);

The searching and the printing out looks like this. As you can see I can also tell the line number but I have no idea how to print out the other lines. I was thinking about uploading an array or something like this but don't know where to start.

You could use a queue (eg a Java LinkedList ) to store the 9 preceding and 5 following lines, around the line you want to match. Then, just print out all lines from the linked list.

public void fajl(String fajlnev, String szeriaszam) throws FileNotFoundException {
    List<String> lines = new LinkedList<>();
    Scanner serialnummer = new Scanner(new File(fajlnev));
    int counter = 5;
    boolean flag = false;

    while (serialnummer.hasNext()) {
        String line = serialnummer.nextLine().toString();
        if (lines.size() >= 9 && !flag) {
            lines.removeFirst();
        }
        lines.add(line);
        if (line.contains(szeriaszam) && !flag) {
            flag = true;
        }
        else if (flag && --counter == 0) {
            break;
        }
    }

    for (String line : lines) {
        System.out.println(line);
    }
}

The logic here is that we start off reading and storing all lines into a linked list. Once the list size reaches 9, and should that occur before we find the matching line, we kick out the oldest line to make room for the latest incoming line. Once we find the matching line, we also add it, and then add 5 more lines, counting down. At the end of the method, we print out the 15 lines, including the matching line, to the console.

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