Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 988
Use your head Avatar asked Jun 24 '13 06:06

Use your head


People also ask

Can you read a file multiple times in Java?

Yes - reading the file multiple times is a solution not a requirement Is there a better solution?

How many lines can BufferedReader read?

The readLine() method of BufferedReader class in Java is used to read one line text at a time.

How do I read BufferedReader?

The read() method of BufferedReader class in Java is used to read a single character from the given buffered reader. This read() method reads one character at a time from the buffered stream and return it as an integer value. Overrides: It overrides the read() method of Reader class.

Is BufferedReader more efficient than FileReader?

BufferedReader is much more efficient than FileReader in terms of performance. FileReader directly reads the data from the character stream that originates from a file.


1 Answers

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);
}

// Read again
for (String result: ans) {
    System.out.println(result);
}
like image 151
4 revs, 3 users 63% Avatar answered Sep 22 '22 02:09

4 revs, 3 users 63%