2013-10-29 39 views
0

我正在java中構建一個小軟件來測試函數和PrintWriter方法。但是當我運行它時,只會打印循環的最後一個數字。例如在奇數文件上只打印99,在偶數文件上只打印100個。打印文件編寫器只寫1個編號

我創建了幾個system.out.println來測試循環是否正常工作,它看起來像是。有誰知道它爲什麼只打印一行?

/** 
* 
* @author bertadevant 
*/ 

import java.io.*; 

public class Filewritermethods { 

    public static void main(String[] args) throws IOException { 

     Numbers(); 

    } 

    public static void Numbers() throws IOException { 

     for (int i =1; i<=100; i++){ 

      EvenOdd(i); 
     } 
} 

    public static void EvenOdd (int n) throws IOException { 

     File Odd = new File ("odd.txt"); 
     File Even = new File ("even.txt"); 
     File All = new File ("all.txt"); 

     PrintWriter all = new PrintWriter (All); 

     all.println(n); 
     all.close(); 

     if (n%2==0){ 

      PrintFile(Even, n); 
      System.out.println ("even"); 
     } 

     else { 
      PrintFile (Odd, n); 
      System.out.println ("odd"); 
     } 

    } 

    public static void PrintFile (File filename, int n) throws IOException { 

     PrintWriter pw = new PrintWriter (filename); 

     if (n!=0) { 
      pw.println(n); 
      System.out.println (n + " printfile method"); 
     } 

     else { 
      System.out.println ("The number is not valid"); 
     } 

     pw.close(); 
    } 
} 

回答

2

你這樣做:

  1. 打開文件
  2. 寫號
  3. 關閉文件
  4. 通過將(1)重新開始。

這樣,您就清除了以前的文件數據。你的邏輯更改爲:

  1. 打開文件
  2. 寫號
  3. 轉到(2)
  4. 完成後,關閉文件。

或者,你也可以選擇通過附加數據寫入到文件中。但在這種情況下,這不是不推薦。 (!只爲教育目的)如果你想嘗試它,你可以嘗試創建自己的PrintWriters這樣的:

PrintWriter pw = new PrintWriter(new FileWriter(file, true)); 
1

默認情況下,PrintWriter覆蓋現有文件。在您的PrintFile方法中,爲每個寫入創建一個新的PrintWriter對象。這意味着您可以覆蓋您之前在PrintFile方法中編寫的所有內容。因此該文件只包含最後一次寫入。要解決此問題,請使用共享的PrintWriter實例。

請注意,按照慣例,方法,在Java領域和變量開始以小寫字母(numbers()evenOdd(...)printFile(...)oddevenfile ...)。這使得您的代碼對其他人更具可讀性。