Java ImageIO.read(File vs URL)

470 views Asked by At

According to the API, the Java's ImageIO (javax.imageio.ImageIO) provides several overloaded methods for the .read() method.

Two of those methods were:

ImageIO.read(File input) 
ImageIO.read(URL input)

The Oracle tutorial website uses the read from file method ImageIO.read(File input). However I've seen many example coded by the programmers here prefer to use the URL approach ImageIO.read(URL input).

Exmaple:

img = ImageIO.read(new File("myImage.png"));
                        vs
img = ImageIO.read(getClass().getResource("images/myImage.png"));

My question is: If I am only coding for a Java Desktop app (and not a Java applet). Is there is significant advantage for using the URL approach over the other?


Note: There is a post with similar title in SO: Using URL or File (in ImageIO.read)

But this question address specifically on IDE. But I am not asking based on any specific IDE, but generally is there any prominent advantage for one over the other?

2

There are 2 answers

5
Andrew Thompson On BEST ANSWER

..is there any prominent advantage for one over the other?

An URL can refer to a place on the internet, a file on the user's local file system, or a resource inside a Jar file - an .

A File can refer to a file on the user's local file system, and.. well, that is about it.

So, unless read/write access is required to the resource, I'd go with the URL since it is more versatile.

0
Rahul On

It is always better to keep your resources inside archive than keeping files in your file system. Suppose you want to distribute the JAR file. Then it will not work properly on other computers . Moreover one might delete those files by mistake . On the other hand JAR archives are meant to be uneditable . Better choice to keep inside JAR. If want to drop from internet , the story is different.