java 写文件 flush_使用 Java 程序写文件时,记得要 flush()

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

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

代码大致是这样的:

48304ba5e6f9fe08f3fa1abda7d326ab.png

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 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

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

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

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

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

遂恍然大悟。

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

48304ba5e6f9fe08f3fa1abda7d326ab.png

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 }

48304ba5e6f9fe08f3fa1abda7d326ab.png

没有 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值