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
Yes - reading the file multiple times is a solution not a requirement Is there a better solution?
The readLine() method of BufferedReader class in Java is used to read one line text at a time.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With