問題代碼:
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寫入