我有一个文本文件,每行一个整数 –
10 20 50
我想阅读和打印这些数字两次甚至多次.我尝试了一些代码而失败了.如何更改代码以打印列表两次?
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
解决方法
现在您可以多次打印.
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); }