码迷,mamicode.com
首页 > 编程语言 > 详细

【java】File的使用:将字符串写出到本地文件,大小0kb的原因

时间:2018-07-07 20:32:54      阅读:176      评论:0      收藏:0      [点我收藏+]

标签: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的原因

标签:code   0kb   display   try   inf   tst   file   dom   ace   

原文地址:https://www.cnblogs.com/sxdcgaq8080/p/9277777.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!