使用 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 掉了。
打住。不要給自己找理由。
再小的程序也有自己的規則/規范,要遵守。