2016-10-02 97 views
1

我想記錄我的程序正在做什麼。目前我使用PrintWriter,但它生成的只是一個空白的txt文件。有人可以請更正我的代碼,如果可能或給任何建議。不打印到文件java

public class Log { 
public static void log(String string){ 
    if(string != null) { 
     System.out.println("log ".concat(string)); 
     try { 
      PrintWriter out=new PrintWriter(new FileWriter("log.txt")); 
      out.println("log ".concat(string)); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

public static void log(String[] strings) { 
    if (strings == null) return; 
    for(String string : strings) { 
     if (string != null) { 
      System.out.println("log ".concat(string)); 
      try { 
       PrintWriter out=new PrintWriter(new FileWriter("log.txt")); 
       out.println("log ".concat(string)); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

回答

0

你必須刷新PrintWriter的得到該文件中寫入數據

PrintWriter out = new PrintWriter(new FileWriter("log.txt")); 
out.println("log ".concat(string)); 
out.flush(); 

如果您與寫入文件,你應該關閉的PrintWriter這也將導致寫

數據進行
out.close(); 
0

您必須關閉該文件。就像這樣:

PrintWriter out=new PrintWriter(new FileWriter("log.txt")); 
out.println("log ".concat(string)); 
out.close(); 

順便說一句,你可以讓你的第二個方法更清潔:

public static void log(String[] strings) { 
    if (strings == null) return; 
    for(String string : strings) { 
     log(string); 
    } 
} 

你複製粘貼相同的代碼任何時候,你應該尋找一種方式來使用封裝/方法調用來刪除重複的代碼。如果需要的話,以後可以更容易地進行更改。