差異處
這裏顯示兩個版本的差異處。
java:sonarlint:fixbug:s2095 [2020/08/02 15:45] tony 建立 |
java:sonarlint:fixbug:s2095 [2023/06/25 09:48] |
||
---|---|---|---|
行 1: | 行 1: | ||
- | {{tag>SonarLint}} | ||
- | ====== SonarLint | Resources should be closed (java:S2095) ====== | ||
- | ===== Problem ===== | ||
- | 以下是一個蠻常見的stream寫法,使用後透過close去關閉: | ||
- | <code java> | ||
- | BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dirFile)); | ||
- | int count; | ||
- | byte data[] = new byte[BUFFER]; | ||
- | while ((count = tais.read(data, 0, BUFFER)) != -1) { | ||
- | bos.write(data, 0, count); | ||
- | } | ||
- | bos.close(); | ||
- | | ||
- | setPermission(dirFile, entry.getMode()); | ||
- | </code> | ||
- | 但這個寫法在stream操作過程中,如果發生了例外,將導致steam沒關閉而造成memory leak。\\ | ||
- | ===== How to fix? ===== | ||
- | 解決方式有兩種,一種是使用try-finally,並將close放在finally block中;另外一種就是直接使用try-with-resources寫法: | ||
- | <code java> | ||
- | try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dirFile));) { | ||
- | int count; | ||
- | byte data[] = new byte[BUFFER]; | ||
- | while ((count = tais.read(data, 0, BUFFER)) != -1) { | ||
- | bos.write(data, 0, count); | ||
- | } | ||
- | } | ||
- | setPermission(dirFile, entry.getMode()); | ||
- | </code> | ||
- | ===== ===== | ||
- | ---- | ||
- | \\ | ||
- | ~~DISQUS~~ |