NPrasad NPrasad - 2 months ago 6
Java Question

Read chunk of data from a file using java 8

I need to read a text file using java 8. I can read the entire file. But my problem is how can I read only a part of the file.

Example:
I need to read data in between

{AAAA} {/AAAA}
. How can I do this using java 8 and older versions?

{AAAA}
This is the detailed description. This needs to be printed in the book
{/AAAA}
{BBBB}
Sample Code 1
Sample Code 2
Sample Code 3
{/BBBB}

Answer

The best thing you can do is to read your file line by line until you reach your patterns by doing something like that:

try (BufferedReader br = new BufferedReader(
     new InputStreamReader(new File(file), charset))
 ) {
    String line;
    boolean start = false;
    // Read the file line by line
    while ((line = br.readLine()) != null) {
        if (start) {
            // Here the start pattern has been found already
            if (line.equals("{/AAAA}")) {
                // The end pattern has been reached so we stop reading the file
                break;
            }
            // The line is not the end pattern so we treat it
            doSomething(line);
        } else {
            // Here we did not find the start pattern yet
            // so we check if the line is the start pattern
            start = line.equals("{AAAA}");
        }
    }
}

This way you only read your file until you reach the end pattern which will be more efficient than reading the entire file.