2

If I pass GeoTiffReader a File instance which has been marked as deleteOnExit() that file will not be deleted on exit.

File geotiffFile = Paths.get("geotools-test.tiff").toFile();
geotiffFile.deleteOnExit();
GeoTiffReader reader = new GeoTiffReader(geotiffFile);
reader.read(null);

To isolate the problem I tried a version without the GeoTiffReader which works as expected:

File geotiffFile = Paths.get("geotools-test.tiff").toFile();
geotiffFile.deleteOnExit();
Files.readAllBytes(geotiffFile.toPath());

I suspect GeoTiffReader isn't releasing the file handle at exit. Full code:

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import org.geotools.gce.geotiff.GeoTiffReader;

public class GeoTiffReaderLingeringHandles
{
    public static void main(String[] args)
        throws IOException
    {
        main_working(args);
        // main_broken(args);
    }

    public static void main_working(String[] args)
        throws IOException
    {
        File geotiffFile = Paths.get("geotools-test.tiff").toFile();
        geotiffFile.deleteOnExit();
    }

    public static void main_broken(String[] args)
        throws IOException
    {
        File geotiffFile = Paths.get("geotools-test.tiff").toFile();
        geotiffFile.deleteOnExit();
        GeoTiffReader reader = new GeoTiffReader(geotiffFile);
        reader.read(null);
    }
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
spt5007
  • 178
  • 1
  • 7

2 Answers2

1

You need to dispose() of a GridCoverageReader so that it has a chance to release the underlying inputStream which would prevent a brain dead operating system deleting the file later.

Ian Turton
  • 10,018
  • 1
  • 28
  • 47
1

To fix your problem, I believe you need to dispose of the planarimage. Using your code as an example,

public static void main_broken(String[] args)
    throws IOException
{
    File geotiffFile = Paths.get("geotools-test.tiff").toFile();
    geotiffFile.deleteOnExit();
    GeoTiffReader reader = new GeoTiffReader(geotiffFile);
    GridCoverage2D result = reader.read(null);
    PlanarImage planarImage = (PlanarImage) result.getRenderedImage();
    ImageUtilities.disposePlanarImageChain(planarImage);
}

This should delete your GeoTiffFile on exit.

Justin L
  • 375
  • 2
  • 10