Matchbox2093 Matchbox2093 - 8 days ago 5
Java Question

bufferedReader - reading out lines in sections from a text file

I have a text file which has a format similar to this:

===Header1====

LINE1

LINE2

LINE3

===Header2====

LINE1

LINE2

LINE3

What I'm trying to do is parse these out individually to a String variable, so when the reader detects

"====Header1===="
, it will also read all lines underneath til it detects
"===Header2==="
, which will be variable Header1 and so on

Im having issues at the moment with reading out the lines till it detects the next header. I was wondering could anyone shed some light on this? Here is what i have so far

try (BufferedReader br = new BufferedReader(new FileReader(FILE))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if (sCurrentLine.startsWith("============= Header 1 ===================")) {
System.out.println(sCurrentLine);
}
if (sCurrentLine.startsWith("============= Header 2 ===================")) {
System.out.println(sCurrentLine);
}
if (sCurrentLine.startsWith("============= Header 3 ===================")) {
System.out.println(sCurrentLine);
}
}
} catch (IOException e) {
e.printStackTrace();
}

Answer

You can create a readLines() method which will read the lines till the next header and loads the lines to an arraylist, call readLines() from main() as shown in the below code with inline comments:

 public static void main(String[] args) {

     BufferedReader br = null;
      try {
           br = new BufferedReader(new FileReader(new File(FILE)));

           //read the 2rd part of the file till Header2 line
           List<String> lines1 = readLines(br, 
                              "============= Header 2 ===================");

           //read the 2rd part of the file till Header3 line
           List<String> lines2 = readLines(br, 
                              "============= Header 3 ===================");

            //read the 3rd part of the file till end        
            List<String> lines3 = readLines(br, "");

        } catch (IOException e) {
             e.printStackTrace();
        } finally {
            //close BufferedReader
        }
   }

   private static List<String> readLines(BufferedReader br, String nextHeader) 
                                                  throws IOException {
                 String sCurrentLine;
                 List<String> lines = new ArrayList<>();
                 while ((sCurrentLine = br.readLine()) != null) {
                     if("".equals(nextHeader) || 
                         (nextHeader != null &&      
                       nextHeader.equals(sCurrentLine))) {
                         lines.add(sCurrentLine);
                     }
                 }
                 return lines;
      }