許多I/O資源,在Java中,如InputStream和OutputStream需要所討論here,要當他們與完成關閉。如何在Java中查找未封閉的I/O資源?
如何搜索我的地方項目中,這些資源沒有被關閉,如這種類型的錯誤:
private void readFile(File file) throws IOException {
InputStream in = new FileInputStream(file);
int nextByte = in.read();
while (nextByte != -1) {
// Do something with the byte here
// ...
// Read the next byte
nextByte = in.read();
}
// Oops! Not closing the InputStream
}
我已經嘗試了一些靜態分析工具如PMD和FindBugs的,但他們沒有標誌上面的代碼爲錯誤的。
FindBugs的似乎是能夠檢測到這一點,雖然:http://stackoverflow.com/questions/2570820/findbugs-may-fail-to-close-stream-is-this-valid-in-case-of- InputStream的 – Thilo
聽起來像是你需要調整哪些規則FindBugs的檢查 –