this is a stupid question, but I can't figure it out. Do I need to close Object passed as parameters inside a try with resources ?
here it is an example:
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
...
}
Do I need to call
sw.close();
after the try block ? or does it close automatically all the Autocloseable objects passed as parameters ?
The implicit invocation of close
on your PrintWriter
will actually close the underlying Writer
as well.
See following example:
StringWriter sw = new StringWriter() {
@Override
public void close() throws IOException {
super.close();
System.out.println("closed");
}
};
try (PrintWriter pw = new PrintWriter(sw)) {};
Output
closed
PrintWriter
's close
method will close StringWriter
as well (but... yes, there is nothing to close there). It is not a common case for other wrappers.
You can pass both objects in try
block to make sure they will be closed:
try (StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
....
}
Since both of these two classes implement AutoClosable
interface, you can try:
try(
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)
) { ... }
It will automatically close both of these objects.
Add a finally block and close objects passed.This is because finally block is always executed whether there is an exception or not.
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
...
}finally{
sw.close();
}
You can put multiple items inside try-with-resources initialization block:
try (final StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
// ...
} catch (IOException e) {
// ...
}
Both of them will be closed automatically.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.