coobird / thumbnailator

Thumbnailator - a thumbnail generation library for Java
MIT License
5.14k stars 784 forks source link

FileImageSource stream not closed on exception #143

Closed simb0 closed 4 years ago

simb0 commented 5 years ago

To respect the wish not to create pull requests but an issue... here it comes.

If an error occurs while reading the local stream in the FileImageSource, the created stream will not be closed, so the src file cannot be deleted.

The error can be reproduced with this test:

@Test
public void broken_image_should_be_deletable_after_read() throws IOException {
    File sourceFile = File.createTempFile("tempfile", "_thumbnailatortest.jpg");

    //some broken image input
    InputStream is = new InputStream() {
        private long size = 0;
        private Random r = new Random();
        int[] jpg = new int[] {0xFF, 0xD8, 0xFF, 0xE0};
        private int i = -1;

        @Override
        public int read() {
            if(size > 1024*10)
                return -1;
            size++;

            i++;
            if(i >= jpg.length)
                return r.nextInt();

            return jpg[i];
        }
    };

    FileOutputStream os = new FileOutputStream(sourceFile);
    byte[] buffer = new byte[1024];
    int bytesRead;
    //read from is to buffer
    while((bytesRead = is.read(buffer)) !=-1){
        os.write(buffer, 0, bytesRead);
    }
    is.close();
    //flush OutputStream to write any buffered data to file
    os.flush();
    os.close();

    FileImageSource source = new FileImageSource(sourceFile);

    try {
        source.read();
    } catch (Exception e) {
        //i know its broken...
    }

    //try to delete the broken file
    sourceFile.delete();

    assertFalse(sourceFile.exists());
}

With a try.. finally block this can be solved possibly quite fast.

coobird commented 4 years ago

Reproduced issue on Windows.