2016-10-02 184 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); 
    } 
} 

你复制粘贴相同的代码任何时候,你应该寻找一种方式来使用封装/方法调用来删除重复的代码。如果需要的话,以后可以更容易地进行更改。