GeoTiffReader阻止deleteOnExit

时间:2017-01-18 15:34:38

标签: java geotools geotiff

如果我向GeoTiffReader传递一个已标记为deleteOnExit()的File实例,则该文件在退出时不会被删除。

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

为了隔离问题,我尝试了一个没有按预期工作的GeoTiffReader的版本:

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

我怀疑GeoTiffReader在退出时没有释放文件句柄。完整代码:

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);
    }
}

2 个答案:

答案 0 :(得分:1)

你需要dispose()一个GridCoverageReader,以便它有机会释放潜在的inputStream,以防止脑死机操作系统稍后删除该文件。

答案 1 :(得分:1)

要解决您的问题,我相信您需要处理平台图像。以您的代码为例,

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);
}

这应该在退出时删除您的GeoTiffFile。