RanjitRock
RanjitRock

Reputation: 1441

How to read lines above and below a particular linenumber in java?

I need to parse a log file which is in txt format.

I need to match the String and read above and below lines of the matched String.

I need to do something similar to grep -A 30 -B 50 'hello'.

If You have any other suggestions to do it you are welcome.

Upvotes: 0

Views: 1155

Answers (3)

Kuldeep Jain
Kuldeep Jain

Reputation: 8598

You may use following code(uses java 5 api java.util.Scanner):

    Scanner scanner = new Scanner(new File("YourFilePath"));
    String prev = null;
    String current;
    while (scanner.hasNextLine())
    {
        current = scanner.nextLine();
        if (current.contains("YourRegEx"))
            break;
        else
            prev = current;
    }
    String next = scanner.nextLine();

You may want to add additional checks for prev being not null and Calling scanner.hasNextLine() before String next = scanner.nextLine()

Upvotes: 0

Marcelo
Marcelo

Reputation: 4608

pseudocode:

initialize a Queue
for each line
    if line matches regex
        read/show lines from queue;
        read/show next lines;
    else {
        if queue size > 30
             queue.remove() // removes head of the queue
        add this line to queue;
    }

You can use BufferedReader to read a file line by line, Pattern to check the line against a regular expression, and Queue to store previous lines.

Upvotes: 1

Alex Calugarescu
Alex Calugarescu

Reputation: 848

Read the file line by line, and match your string (either regexp or String.indexOf("")). Keep the previous n lines in memory so when you've matched your string you can print them. Use BuffereReader.readLine() to read the file line by line (note that using the BufferedReader is actually more complicated because you cannot jump back). Or for more flexibility RandomAccessFile. With this method you can mark your position, print the next m lines and then jump back to continue your search from where you left it.

Upvotes: 1

Related Questions