NPrasad NPrasad - 4 months ago 12
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.

I need to read data in between

. How can I do this using java 8 and older versions?

This is the detailed description. This needs to be printed in the book
Sample Code 1
Sample Code 2
Sample Code 3


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
            // The line is not the end pattern so we treat it
        } 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.