2016-01-17 54 views
0

當我在Java控制檯中打印出來時,下面的程序完美地工作,但是當我嘗試追加要放入文本文件的程序時,它僅將1/5的學生平均值打印到附加的文本文件中。如何將java輸出附加到文本文件?

Bobby, average = 93 

我想這是所有印刷5學生的平均水平爲提前讓

Agnes, average = 76 
Bufford, average = 91 
Julie, average = 94 
Alice, average = 39 
Bobby, average = 93 

感謝。

每次它進入這一行時間
import java.util.*; 
import java.io.*; 
public class StudentAverage { 
public static void main(String[]args) throws IOException { 


Scanner scanner = new Scanner(new   
File("D:\\School\\StudentGrades.txt")); 

while (scanner.hasNextLine()) { 

    Scanner scanners = new Scanner(scanner.nextLine()); 

    String name = scanners.next(); 
    double total = 0; 
    int num = 0; 

    while (scanners.hasNextInt()) { 
     total += scanners.nextInt(); 
     num++; 
    } 

    PrintStream output = new PrintStream (("D:\\School\\WriteStudentAverages.txt")); 
    output.print(name + ", average = " + (Math.round(total/num))); 
    output.flush(); 
} 
scanner.close(); 
} 
} 

回答

3
PrintStream output = new PrintStream (("D:\\School\\WriteStudentAverages.txt")); 

,它會刪除該文件,打開一個新的文件,僅增加當前行。在循環之前寫下這一行,然後在循環中按原樣保留其他代碼。

+0

謝謝!很棒。 –

0

要附加您的輸出/文本文件,您必須使用不同的書寫方式。

我也建議使用try-with-resource塊來避免memeory泄漏。

try (OutputStream output = new FileOutputStream("myFile.txt", true); 
     Writer writer = new OutputStreamWriter(output)) { 
    writer.write(name + ", average = " + (Math.round(total/num)) + '\n'); 
} 

您不必刷新/關閉它們在你的代碼手動

0

有幾個小故障。由於您需要使用try/resource-construct同時管理Scanner和PrintWriter,因此我寧願將輸入和輸出例程分開,並將文件的相關內容臨時讀入內存。

這裏有一個想法:

LinkedHashMap<String, Integer> students = new LinkedHashMap<>(); 

// Input routine 
try (Scanner scanner = new Scanner(new File("D:\\School\\StudentGrades.txt"))) { 
    while (scanner.hasNextLine()) { 
     try (Scanner scanners = new Scanner(scanner.nextLine())) { 
      String name = scanners.next(); 
      int total = 0; 
      int num = 0; 

      while (scanners.hasNextInt()) { 
       total += scanners.nextInt(); 
       num++; 
      } 

      students.put(name, (int) Math.round((double)total/num)); 
     }  
    } 
} 
catch (FileNotFoundException e) { 
    // do something smart 
} 

// Output routine 
try (PrintStream output = new PrintStream ("D:\\School\\WriteStudentAverages.txt")) { 
    for (Entry<String, Integer> student : students.entrySet()) { 
     output.println(student.getKey() + ", average = " + Integer.toString(student.getValue()));  
    } 
} 
catch (FileNotFoundException e) { 
    // do something smart 
} 

以上,您還可以在您的main() - 方法的簽名擺脫那個討厭的throws IOException。取而代之的是,現在有兩個漂亮的異常處理程序(兩個卡扣塊),你可以把

  • 輸入文件還沒有被發現的情況下,觸發一些邏輯的骨架/不可讀取(第一個catch)
  • 輸出文件不可寫/無法創建(第二次捕獲)
相關問題