使用 Java 程序写文件时,记得要 flush()
2015-02-05 15:54
274 查看
使用 Java 程序往磁盘写文件时碰到了这样的问题:文件写不全。
假如内容(StringBuffer/StringBuilder)有 100W 个字符,但是通过 Java 程序写到文件里的却不到 100W ,部分字符不见了。
代码大致是这样的:
文件是生成了。可内容不对,只写入了部分字符。
我甚至怀疑,是不是 StringBuffer/StringBuilder 也有长度限制?因为每次写入文件的字符都一样多。
现在想想,真是图样图森破啊。
后来,经旁人提醒,你 flush 了吗?
遂恍然大悟。
正确的代码应该是这样的:
没有 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
假如内容(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
相关文章推荐
- 使用 Java 程序写文件时,记得要 flush()
- 使用Java程序来实现HTTP文件的队列下载
- 一个使用JAVA编写的类似按键精灵的程序,支持脚本文件编写(含源代码)
- 使用java程序读取配置文件中的相关属性值-asp.net关注
- Java桌面应用安装部署、安装程序制作(exe4j + Inno Setup)——之三:使用exe4j生成EXE可执行文件
- 使用bat(批处理文件)启动java程序
- 使用.bat文件运行Java程序的一个示例
- 使用.bat文件在Windows下运行Java程序时怎样避免DOS窗口
- java程序使用Exe4j生成可执行文件(做个笔记)
- 使用fat jar和exe4j把java程序打包成exe执行文件
- 如何使用java程序打开一个文件?
- 一个使用JAVA编写的类似按键精灵的程序,支持脚本文件编写(含源代码)
- 使用.bat文件在Windows下运行Java程序时怎样避免DOS窗口
- Chap5:使用JNI技术实现java程序调用第三方dll(c/c++)文件的功能
- 一个使用JAVA编写的类似按键精灵的程序,支持脚本文件编写(含源代码)
- 使用脚本文件(jnlp)来发布Java程序
- 使用java编写程序生成loadrunner参数化文件
- 使用脚本文件(jnlp)来发布Java程序
- 5、 java 编写程序拷贝一个文件, 尽量使用效率高的方式.
- 使用JSmooth将java程序转换成windows上的.exe文件(彻底解决相对目录问题)