GridCoverage2D cannot close file input stream

Description

I have an application that can load a GeoTiff and evaluates it for latitude, longitude position. Later on I want to delete the geotiff file, but does not work because GeoTools is keeping a file lock, because the stream used inside the GridCoverage2D is not closed. I tried calling GridCoverage2D.dispose(true), but that does not help.

Here is my code:

private GridCoverage2D coverage; public void load(File file) { AbstractGridFormat format = GridFormatFinder.findFormat(file); GridCoverage2DReader reader = format.getReader(file); this.coverage = reader.read(null); reader.dispose(); } public double[] evaluate(double latitude, double longitude) { try { Position2D geoPosition = new Position2D(Math.toDegrees(longitude), Math.toDegrees(latitude)); return coverage.evaluate((Position) geoPosition, (double[]) null); } catch (PointOutsideCoverageException e) { return null; } }

I am currently closing the stream via reflection, which works as a workaround:

Class<?> imageReadOpImageClass = Class.forName("com.sun.media.jai.imageioimpl.ImageReadOpImage"); Field imageField = GridCoverage2D.class.getDeclaredField("image"); Field theImageField = RenderedOp.class.getDeclaredField("theImage"); Field readerField = imageReadOpImageClass.getDeclaredField("reader"); Field streamField = TIFFImageReader.class.getDeclaredField("stream"); imageField.setAccessible(true); theImageField.setAccessible(true); readerField.setAccessible(true); streamField.setAccessible(true); Object image = imageField.get(coverage); Object theImage = theImageField.get(image); Object reader = readerField.get(theImage); Object stream = streamField.get(reader); ((Closeable) stream).close();

 

The stream is located at GridCoverage2D coverage -> RenderedOp image -> ImageReadOpImage theImage -> TIFFImageReader reader -> ImageInputStream stream

It seems that there is no chance to close the stream using the public API.

Environment

None

Activity

Show:

Details

Assignee

Reporter

Affects versions

Priority

Created March 7, 2025 at 12:14 PM
Updated March 7, 2025 at 12:22 PM