zoukankan      html  css  js  c++  java
  • 使用 Java 程序写文件时,记得要 flush()

    使用 Java 程序往磁盘写文件时碰到了这样的问题:文件写不全。

    假如内容(StringBuffer/StringBuilder)有 100W 个字符,但是通过 Java 程序写到文件里的却不到 100W ,部分字符不见了。

    代码大致是这样的:

    1     private void writeToDisk() throws Exception {
    2         File file = new File("FILE_PATH");
    3         OutputStreamWriter osw = null;
    4         osw = new OutputStreamWriter(new FileOutputStream(file));
    5 
    6         osw.write("A HUGE...HUGE STRING");
    7     }

    文件是生成了。可内容不对,只写入了部分字符。

    我甚至怀疑,是不是 StringBuffer/StringBuilder 也有长度限制?因为每次写入文件的字符都一样多。

    现在想想,真是图样图森破啊。

    后来,经旁人提醒,你 flush 了吗?

    遂恍然大悟。

    正确的代码应该是这样的:

     1   private void writeToDisk2() {
     2         File file = new File("FILE_PATH");
     3         OutputStreamWriter osw = null;
     4         try {
     5             osw = new OutputStreamWriter(new FileOutputStream(file));
     6 
     7             osw.write("A HUGE...HUGE STRING");
     8 
     9         } catch (FileNotFoundException e) {
    10             e.printStackTrace();
    11         } catch (IOException e) {
    12             e.printStackTrace();
    13         } finally {
    14             try {
    15                 osw.flush();
    16                 osw.close();
    17             } catch (IOException e) {
    18                 e.printStackTrace();
    19             }
    20         }
    21     }

    没有 flush , 直接 close 也行。

    不过 Java 官方文档提醒:close之前,要 flush 一下。

    Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.

    不该犯这样的错误的。

    上学的时候老师都教了,打开的流一定要记得关闭

    〇老师,对不起,我错了。

    因为只是一个小的测试程序,没有那么规范地写 try/catch ,直接都 throw 掉了。

    打住。不要给自己找理由。

    再小的程序也有自己的规则/规范,要遵守。

  • 相关阅读:
    贝叶斯思想的实质之我见
    强化学习基础概念理解
    Thinkpad x200用户只能放弃生化危机5(PC版), 希望能全速运行星际争霸2!
    This is it
    今天自己掏腰包去买联通iPhone有几位?
    今天是我的生日:)
    2009已经到来 / 2009 Just the Beginning
    好评如潮的PS3游戏《抵抗2 Resistance2》你玩了吗?
    生化危机5 / BIOHAZARD5 简直就是一款完美的印钞机?(+2009.4.9)
    一部好电影《第九区 District 9》
  • 原文地址:https://www.cnblogs.com/memory4young/p/do-remember-close-the-stream-finally-in-java.html
Copyright © 2011-2022 走看看