Reputation: 5055
Lets consider image.png
stored inside one of the project's package named icons, I usually get the icons via getResource()
method :
String imgPath = getClass().getResource("/icons/image.png").toString();
//no problem with creating an ImageIcon with this path
Image img = new ImageIcon(imgPath).getImage();
//but the problem occures when trying to open this image through Desktop
//try-catch
Desktop.getDesktop().open(imagePath);
//or
File imgFile = new File(imgPath);
//error, this file does not exist!
I noticed that constructing a string from the URL gives the output that starts with file:/....
, it makes no problem with loading the image, but opening the file not possible until removing file:/
.
What's the benifit of file:/
that added to the string?
I thought that maybe the path is to a file, but I was wrong, even targeting to the folders gives this output.
Upvotes: 2
Views: 287
Reputation: 7889
The method Class.getResources(String)
returns a URL
. This URL
may be that of a local file, in which case it will begin with the file:/
protocol. However, your application or this class may run from a JAR file, and the resource may be contained in a JAR file. Sun created the jar:/
protocol for these cases. Then, the URL
might be stringified as jar:file:/myapp.jar!/com/azad/images/image.png
. So, instead of using file-based methods, use URL-based methods:
URL imgURL = getClass().getResource("/icons/image.png");
//no problem with creating an ImageIcon with this URL
Image img = new ImageIcon(imgURL).getImage();
ImageIcon
has a constructor that takes a URL
. Look at the JarURLConnection class too. You can't depend on Desktop
to open your URL for you; that class only handles files. If your URL doesn't point at a plain file, you can't remove the file:/
from the string.
I did edit your post: you used img
twice.
Upvotes: 1
Reputation: 36423
Its a URL path specific to files. Kinda how like web URLs have http://, https:// or ftp:// URL for file keeps that syntax thus file:/ was born .
For example copy an image like test.jpg to your C drive.
Than open your browser and type: file:/c:/test.jpg
hit ENTERand the image should be loaded.
What's the benefit of file:/ that added to the string?
No real benefits, besides the fact it becomes a valid URL, it can only be used as a URL and not as a valid path to a file, for that you would omit file:/ as you have seen
See file URI scheme for more
Upvotes: 1