walnutmon walnutmon - 1 year ago 82
Java Question

Java/Groovy File IO Replacing an Image File with it's own Contents - Why Does This Work?

I have some JPG files that need to be replaced at runtime with a JFIF standardized version of themselves (we are using a vendor that gives us JPG that do not have proper headers so they don't work in certain applications)... I am able to create a new file from the existing image, then get a buffered image from that file and write the contents right back into the file without having to delete it and it works...

imageSrcFolder.eachFileMatch ( ~/.*\.jpg/, {
BufferedImage bi = ImageIO.read( it )
ImageIO.write( bi, "jpg", it )

The question I have is why? Why doesn't the file end up doubled in size? Why don't I have to delete it first? Why am I able to take a file object to an existing file and then treat it as if it were a brand new one? It seems that what I consider to be a "file" is not what the File object in java actually is, or else this wouldn't work at all.

My code does exactly what I want it to do, but I'm not convinced it always will... it just seems way too easy

Answer Source

The JavaDoc for ImageIO.write includes this phrase:

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

This is assuming that it is a File, as you used it in both the read and write operations.