Updated code samples to use more modern try-with-resource syntax.

This commit is contained in:
Harald Kuhr 2020-11-23 08:55:50 +01:00
parent 1b4d25342f
commit 1fe0bdd41f

View File

@ -79,10 +79,8 @@ The plugins are discovered automatically at run time. See the [FAQ](#faq) for mo
If you need more control of read parameters and the reading process, the common idiom for reading is something like: If you need more control of read parameters and the reading process, the common idiom for reading is something like:
```java ```java
// Create input stream // Create input stream (in try-with-resource block to avoid leaks)
ImageInputStream input = ImageIO.createImageInputStream(file); try (ImageInputStream input = ImageIO.createImageInputStream(file)) {
try {
// Get the reader // Get the reader
Iterator<ImageReader> readers = ImageIO.getImageReaders(input); Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
@ -119,10 +117,6 @@ try {
reader.dispose(); reader.dispose();
} }
} }
finally {
// Close stream in finally block to avoid resource leaks
input.close();
}
``` ```
Query the reader for source image dimensions using `reader.getWidth(n)` and `reader.getHeight(n)` without reading the Query the reader for source image dimensions using `reader.getWidth(n)` and `reader.getHeight(n)` without reading the
@ -144,10 +138,8 @@ if (!writers.hasNext()) {
ImageWriter writer = writers.next(); ImageWriter writer = writers.next();
try { try {
// Create output stream // Create output stream (in try-with-resource block to avoid leaks)
ImageOutputStream output = ImageIO.createImageOutputStream(file); try (ImageOutputStream output = ImageIO.createImageOutputStream(file)) {
try {
writer.setOutput(output); writer.setOutput(output);
// Optionally, listen to progress, warnings, etc. // Optionally, listen to progress, warnings, etc.
@ -160,10 +152,6 @@ try {
// Optionally, provide thumbnails and image/stream metadata // Optionally, provide thumbnails and image/stream metadata
writer.write(..., new IIOImage(..., image, ...), param); writer.write(..., new IIOImage(..., image, ...), param);
} }
finally {
// Close stream in finally block to avoid resource leaks
output.close();
}
} }
finally { finally {
// Dispose writer in finally block to avoid memory leaks // Dispose writer in finally block to avoid memory leaks
@ -446,7 +434,7 @@ Servlet support
## License ## License
The project is distributed under the OSI approved [BSD license](http://opensource.org/licenses/BSD-3-Clause): This project is provided under the OSI approved [BSD license](http://opensource.org/licenses/BSD-3-Clause):
Copyright (c) 2008-2020, Harald Kuhr Copyright (c) 2008-2020, Harald Kuhr
All rights reserved. All rights reserved.