【java】File的使用:將字串寫出到本地檔案,大小0kb的原因

來源:互聯網
上載者:User

標籤:code   0kb   display   try   inf   tst   file   dom   ace   

實現方法:

   暫時寫一種方法,將字串寫出到本地檔案,以後可以補充更多種方法:

 public static void main(String[] args) {        /**         * ==============準備一些資料-start===============         */        String fileName = UUID.randomUUID().toString();        String filePath = "E:/sxContext"+ "/"+ fileName;        String content = "";        StringBuilder stringBuilder = new StringBuilder();        int a = 10;        for (int i = 0; i < a; i++) {              stringBuilder.append(UUID.randomUUID().toString()+"\n\n");        }        content = "測試文字檔:\r\n" + stringBuilder.toString();        /**         * ==============準備一些資料-end===============         */        /**         * ===============start-將字串寫出到本地檔案=================         */        File file = new File(filePath);        //如果父級檔案件不存在 則新建立        File parentFile = file.getParentFile();        if (!parentFile.exists()){            parentFile.mkdirs();        }        FileWriter fw = null;        BufferedWriter bw = null;        try {            if (!file.exists()){                file.createNewFile();            }             fw = new FileWriter(file);             bw = new BufferedWriter(fw);             bw.write(content);             bw.flush();        } catch (IOException e) {            e.printStackTrace();        }finally {            try {                bw.close();                fw.close();            } catch (IOException e) {                e.printStackTrace();            }        }        /**         * ===============end-將字串寫出到本地檔案=================         */    }
View Code

 

【注意,

bw.write(content);

可以在for迴圈中多次執行!!!

 

如果 擔心,可以在執行完bw.write()

執行:

bw.flush();

】

 

 

=======================

至於將常值內容寫出到本地檔案中,不管你寫出的本地檔案是不是txt檔案或者沒有尾碼的檔案,只要

1.父級目錄不存在,建立父級目錄

2.file檔案判斷exist() 如果沒有就createNewFile()

3.將文本寫出到本地

4.flush()

5.close()

 

出現本地檔案0kb大小,可能會有以下幾種原因:

1.fileName 中也就是要建立的檔案名稱  中包含了 非法字元,最常見的非法字元就是:冒號  

2.要麼就是沒有執行close()正常關閉流

3.flush()方法可以不用執行 

 

【java】File的使用:將字串寫出到本地檔案,大小0kb的原因

聯繫我們

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