You should do it using the try-with-resources statement. Given below is an excerpt from the Oracle's tutorial on The try-with-resources Statement which clearly states the benefit of using it:
Prior to Java SE 7, you can use a finally
block to ensure that a
resource is closed regardless of whether the try
statement completes
normally or abruptly. The following example uses a finally
block
instead of a try-with-resources statement:
static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}
However, in this example, if the methods readLine
and close
both throw
exceptions, then the method readFirstLineFromFileWithFinallyBlock
throws the exception thrown from the finally
block; the exception
thrown from the try
block is suppressed. In contrast, in the example
readFirstLineFromFile
, if exceptions are thrown from both the try
block and the try-with-resources statement, then the method
readFirstLineFromFile
throws the exception thrown from the try
block;
the exception thrown from the try-with-resources block is suppressed.
In Java SE 7 and later, you can retrieve suppressed exceptions; see
the section Suppressed Exceptions for more information.
Using the try-with-resources statement, you can write your method as follows:
public String toJson() throws Exception {
String json = null;
try (ByteArrayOutputStream bas = new ByteArrayOutputStream()) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(bas, this);
json = new String(bas.toByteArray());
}
return json;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…