Reputation: 157
public StringBuffer readFile(final File inputFile) {
String tempLine; // variable declaration
Logger log = Logger.getLogger("Error Message");
try {
final FileReader fileReader = new FileReader(inputFile);
final BufferedReader bufferedReader = new BufferedReader(fileReader);
final StringBuffer content = new StringBuffer();
while((tempLine=bufferedReader.readLine())!=null) {
content.append(tempLine);
content.append(System.getProperty("line.separator"));
}
}
catch(FileNotFoundException e) {
log.log(Level.WARNING, "File not found", e);
}
catch (IOException e) {
log.log(Level.WARNING, "Couldn't Read file", e);
}
finally {
bufferedReader.close();
fileReader.close();
}
return content;
}
The variable fileReader and bufferedReader declared as final in try block cannot be used in finally block. I can't declare them outside try block, because they might throw exception. I want the variables to be final too.
Upvotes: 0
Views: 338
Reputation: 9650
Since Java 7, you can write things like that:
public StringBuffer readFile(final File inputFile) {
String tempLine; // variable declaration
Logger log = Logger.getLogger("Error Message");
final StringBuffer content = new StringBuffer();
try (final FileReader fileReader = new FileReader(inputFile);
final BufferedReader bufferedReader = new BufferedReader(fileReader)){
while((tempLine=bufferedReader.readLine())!=null) {
content.append(tempLine);
content.append(System.getProperty("line.separator"));
}
}
catch(FileNotFoundException e) {
log.log(Level.WARNING, "File not found", e);
}
catch (IOException e) {
log.log(Level.WARNING, "Couldn't Read file", e);
}
return content;
}
Here fileReader
and bufferedReader
are implicitly closed.
Upvotes: 0
Reputation: 768
If you use at least Java 7 you can use try-with-resources Statement to close your resources. Here's the code:
public StringBuffer readFile(final File inputFile) {
String tempLine; // variable declaration
Logger log = Logger.getLogger("Error Message");
try (final FileReader fileReader = new FileReader(inputFile)) {
try (final BufferedReader bufferedReader = new BufferedReader(fileReader)) {
final StringBuffer content = new StringBuffer();
while((tempLine=bufferedReader.readLine())!=null) {
content.append(tempLine);
content.append(System.getProperty("line.separator"));
}
return content;
}
} catch (FileNotFoundException e) {
log.log(Level.WARNING, "File not found", e);
} catch (IOException e) {
log.log(Level.WARNING, "Couldn't Read file", e);
}
// return null or throw exception;
}
Upvotes: 1