"I/O resource opened but not safely closed" inspection erroneous ?
BufferedReader bufferedReader = null;
String line;
try {
bufferedReader = new BufferedReader(new FileReader(inFile));
while ((line = bufferedReader.readLine()) != null) {
log.info(line);
}
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
In IntelliJ 8.x the code inspection reports this as an error although the resource is being closed in a finally block.
In IntelliJ 7.x this was ok.
Is this a known bug in 8.x ?
请先登录再写评论。
you''re calling 2 reader constrcutors in the same statement.
as soon as FileReader one completes you have a reader you need to close, so if BufferedReader constrcutor fails for some reason, you'll leak a resource (bufferedReadeer == null, so no close)
Thanks I didn't think about this, but it doesn't look like that this is the solution for this problem.

I have a more simple example with the same problem:
FileInputStream in = null;
try {
in = new FileInputStream("xxx");
int i = in.read();
} finally {
if (in != null) {
in.close();
}
}
well I guess the inspection is telling you should rather do :
FileInputStream in = new FileInputStream("xxx");
try {
int i = in.read();
} finally {
in.close();
}
If you were catching exceptions it wouldn't be as nice, but just for finally this is the best way as far as I can tell : no need to test in for nullity and if the constructor ever fails you won't even enter the try block
Thanks, thats it.
I could have figured this out by myself, if I would just have read the corresponding text "... in front of ..."