This is an adaptation of jcms answer - did it because I didn't like the exception handling in his solution...
We have to decide what to do in case of an exception. That's usually covered in some requirements. Logging is a good idea, but we still have to do something. At least I'd never use the return value to report file content as well as error messages. That's pretty hard to decode for the receiver. One could throw an exception - the usual way, if a missing file or an IO error is an exceptional situation. Or, and that's my suggestion, we define a small class to return both file content and error state:
public class FileContent {
private String fileContent = null;
private Throwable error = null;
public FileContent(String fileContent, Throwable error) {
this.error = error;
this.fileContent = fileContent;
}
// getters for all fields (no setters!)
public boolean isValid() {
return (error == null);
}
}
and the getInput()
method will be like this:
public FileContent getInput(final String fileName) {
final StringBuilder fileContentBuilder = new StringBuilder();
String buffer = null;
BufferedReader reader = null;
Throwable error = null;
try {
reader = new BufferedReader(new FileReader(fileName));
while (buffer = reader.readLine()) {
fileContentBuilder.append(buffer);
}
} catch (FileNotFoundException e) {
error = new RuntimeException("Couldn't find " + fileName, e);
} catch (IOException e) {
error = new RuntimeException("There was an error reading the file.", e);
} finally {
if (inFile != null) {
try {
inFile.close();
} catch (IOException e) {
error = new RuntimeException(
"Couldn't close reader for file " + fileName, e);
}
}
}
return new FileContent(fileContentBuilder.toString(), error);
}
public void useGetInput() {
FileContent content = getInput("your/path/to/your/file");
if (content.isValid()) {
System.out.println(content.getFileContent());
} else {
content.getError().printStackTrace();
}
}
(Improvements; instead of using RuntimeException as a Wrapper, we could define our own exception type)