Skip to content

Instantly share code, notes, and snippets.

@ferromir
Created March 20, 2015 06:09
Show Gist options
  • Select an option

  • Save ferromir/9c1a3fd2bc59220492ab to your computer and use it in GitHub Desktop.

Select an option

Save ferromir/9c1a3fd2bc59220492ab to your computer and use it in GitHub Desktop.
ACR - Java - Release resources
// Bad
public int processFile(String fileName)
throws IOException, FileNotFoundException {
FileInputStream stream = new FileInputStream(fileName);
BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
return 1;
}
// Good
try {
final FileInputStream stream = new FileInputStream(fileName);
try {
final BufferedReader bufRead =
new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = bufRead.readLine()) != null) {
sendLine(line);
}
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// forward to handler
}
}
}
} catch (IOException e) {
// forward to handler
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment