Java 程式 關於Properties 類使用Store方法時不能會覆蓋以前Properties 檔案的內容__JavaSE

來源:互聯網
上載者:User

F:\\Demo.properties 檔案內容:

#\u65B0\u589E\u4FE1\u606F
#Wed Sep 14 11:16:24 CST 2016
province=廣東
tt=近蛋
city=佛山市

java代碼:

        public static void test() throws IOException {
        FileWriter writer = new FileWriter("F:\\Demo.properties");
        FileReader reader = new FileReader("F:\\Demo.properties");
        Properties p = new Properties();
        p.load(reader);

        System.out.println(p);

        p.setProperty("dd", "中建普聯");
        p.setProperty("cc", "狗娃");
        p.setProperty("bb", "狗剩");
        p.setProperty("aa", "鐵蛋");

        p.store(writer, "新增資訊");

        System.out.println(p);

        reader.close();
        writer.close();    
    }  

 控制台輸出:

{}
{dd=中建普聯, aa=鐵蛋, bb=狗剩, cc=狗娃}


出現的問題:

一,讀取的內容為空白,

二,沒有覆蓋以前Properties 檔案的內容


原因是:
FileWriter writer = new FileWriter("F:\\Demo.properties");
FileWriter 開啟檔案的方式預設是覆蓋,就是一旦執行了上面這句,那麼原有檔案中的內容被清空
所以你在還沒有p.load(in);載入Properties的時候就把檔案清空了


修改後如下 :

public static void test() throws IOException {
        
        FileReader reader = new FileReader("F:\\Demo.properties");
        Properties p = new Properties();
        p.load(reader);

        System.out.println(p);

        p.setProperty("dd", "中建普聯");
        p.setProperty("cc", "狗娃");
        p.setProperty("bb", "狗剩");
        p.setProperty("aa", "鐵蛋");

        FileWriter writer = new FileWriter("F:\\Demo.properties");
        p.store(writer, "新增資訊");
        
        System.out.println(p);

        reader.close();
        writer.close();    
    }


 控制台輸出:

{province=廣東, tt=近蛋, city=佛山市}
{dd=中建普聯, province=廣東, tt=近蛋, aa=鐵蛋, bb=狗剩, city=佛山市, cc=狗娃}



問題解決:

是因為FileWriter 開啟檔案的方式預設是覆蓋,

就是一旦執行了上面這句,那麼原有檔案中的內容被清空
所以你在還沒有p.load(in);載入Properties的時候就把檔案清空了
所以 一定要注意開啟 FileWriter 的時機,來把握  FileWriter writer = new FileWriter("F:\\Demo.properties"); 代碼位置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.