2013-12-11 83 views
0

基本上我的程序將數據列入輸出文件,然後我必須能夠讀取輸出文件作爲輸入,以便列出五個最近的數據。 這裏是我的代碼:打印出最近的,而不是使用for循環的第一個輸入?

case 2: options = ""; 
    System.out.println("You have chosen to 'List recent data'" 
         + "The five most recent data is: " + "\n"); 

    String data1; 
    Scanner inFile2 = new Scanner (new FileReader ("Bankbalance.txt")); 

    for (int b=0; b<5; b++) { 
     data1 = inFile2.nextLine(); 
    System.out.println(data1); 
    } 

     break; 

基本上輸出給數據的第一個五件,(我知道這是因爲我要求它來算前五),但是我只是想知道,如果可能顯示最新的數據呢? (來自文本文件底部的數據而非頂部)

回答

0

看到this answer進行一些調整,儘量:

Scanner in = new Scanner (new InputStreamReader (new ReverseLineInputStream(file))); 

for (int b=0; b<5; b++) { 
    String line = in.nextLine(); 
    if (line == null) { 
     break; 
    } 
    System.out.println(line); 
} 
+0

看到我提到,ReverseLineInputStream寫有答案,你必須創建和複製它的代碼到你的項目 –

+0

啊是啊我不好,忘了添加文件,它現在說「ReverseLineInputStream不能解析爲類型」 – user2863681

+0

應該像創建一個新類並在那裏複製代碼一樣簡單 –