I need to download file from a given url, but the thing is I can get files with no extension. In order to figure out what the extension is I wrote the following service:
public String getExtension(String imageURL){
InputStream stream = new URL(imageURL).openStream();
ImageInputStream iis = ImageIO.createImageInputStream(stream);
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
ImageReader reader = imageReaders.next();
String retVal = reader.getFormatName();
closeInputStreamAndDisposeReader(reader);
return retVal;
}
Later on I need to download that image so I wrote:
BufferedImage image = ImageIO.read(imageURL);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write( image, extension, byteArrayOutputStream );
byteArrayOutputStream.flush();
byte[] imageInBytes = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
The problem is that I'm dowloading the file twice - and I would like to use the cache in order to prevent that. Now I read about ImageIO.setUseCache(false);
but it doesn't seems to work (perhaps I'm doing something wrong here).
Edit:
I've noticed that I create the input stream using new URL(imageURL).openStream()
- this is the first download that I'm doing, I think that I should have used one of the ImageIO methods to get that and then the ImageIO.setUseCache(false);
would work.
Am I right?
How can I do that - I tried to use the ImageIO.createImageInputStream(imageURL);
but I got an exception:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.createImageInputStream(Unknown Source)
So, how can I do that?
Thanks.