Use your head Use your head - 5 months ago 230
Java Question

How to read a BufferedReader twice or multiple times?

I have a text file with one integer per row -

10
20
50


I want to read and print these numbers twice or maybe even multiple times. I tried some code and it failed. How do I change my code to print the list twice ?

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class DoubleBuffer {

public static void main(String[] args) {

try {

FileInputStream fstream = new FileInputStream("c:/files/numbers.txt");

BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;

// Read rows
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}

// Read rows again
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}

in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}//try-catch

}// main

}// class

Answer

Now you can print multiple times.

 BufferedReader br = new BufferedReader(new FileReader("D:/log_2071-04-31.txt"));       
           String strLine;
        ArrayList<String> ans= new ArrayList<String>();
         // Read rows
        while ((strLine = br.readLine()) != null) {
         System.out.println(strLine);
              ans.add(strLine);
         } 
         for (String result: ans) {
            System.out.println(result);
        }
Comments