问题代码:
public class Log {
static String fileName;
static PrintWriter pw=null;
public static void setOutputFile(String fileName) {
if(pw!=null) {
pw.close();
}
Log.fileName = fileName;
try {
pw = new PrintWriter(fileName);
} catch(IOException e) {
System.err.println(
"ERROR opening log file:"+e.getMessage());
}
}
------------------------------------------------------------
这样就可以了,但是原因还没想明白
public static void log(String s) {
Log.fileName = s;
if (pw == null) {
setOutputFile(fileName);
}
// try {
// pw = new PrintWriter(fileName);
// } catch (IOException e) {
// System.err.println("ERROR opening log file: " + e.getMessage());
// }
pw.write(s);
pw.write("/n");
}
------------------------------------------------------------
明白了。
之前,你用Log.setOutputFile("c://tmp//Test.txt"); 为pw创建了一个PrintWriter的引用。
在Log.log(s)里面,你又创建了另外一个引用。由于JVM的垃圾收集器总是滞后的,所以,你最早创建PrintWriter还在内存里没释放,并且仍然控制着"c://tmp//Test.txt"。所以,可能出现这样的情况,或者新建PrintWriter写不进去,或者,当最早创建的 PrinterWriter关闭时,覆盖你写好的文件。
try {
pw = new PrintWriter(fileName);
} catch (IOException e) {
System.err.println("ERROR opening log file: " + e.getMessage());
}
------------------------------------------------------------
测试
public static void main(String[] s) {
Log.setOutputFile("c://Test.txt");
// Log.setLogLevel(8);
pw.write("first message.");
Log.log("Hello");
//Log.flush();
Log.close();
}
文件还是空白,所以,不是被覆盖,而是拒绝后面的PrintWriter写入