SonarLint | Resources should be closed (java:S2095)

以下是一個蠻常見的stream寫法,使用後透過close去關閉:

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());
但這個寫法在stream操作過程中,如果發生了例外,將導致steam沒關閉而造成memory leak。

解決方式有兩種,一種是使用try-finally,並將close放在finally block中;另外一種就是直接使用try-with-resources寫法:

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());

  • NIO的Files.walk也是常常被忘記close的stream。