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 掉了。

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

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

    http://www.cnblogs.com/memory4young/p/do-remember-close-the-stream-finally-in-java.html

  • 相关阅读:
    self 和 super 关键字
    NSString类
    函数和对象方法的区别
    求两个数是否互质及最大公约数
    TJU Problem 1644 Reverse Text
    TJU Problem 2520 Quicksum
    TJU Problem 2101 Bullseye
    TJU Problem 2548 Celebrity jeopardy
    poj 2586 Y2K Accounting Bug
    poj 2109 Power of Cryptography
  • 原文地址:https://www.cnblogs.com/cmblogs/p/4275056.html
Copyright © 2011-2022 走看看