PrintWriter寫入檔案問題【轉載綜合】

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.