Java jar path problem
I have a folder named Etc that has an image that I want to use in another file in the same folder, Example.java. So I have Etc \ image.png and Etc \ Example.java. I tried to use "Etc / image.png" as the image path, but it didn't work. How should I do it?
Also, suppose the files were in different packages, how would I go about this?
My main .java classes are in the Main package, for the record.
EDIT:
I used this:
ClassLoader.getSystemClassLoader () getResource ("Etc \ image.png") ;.
You can use Class.getResource()
that uses the classloader to get the url of the resource. For example:
import java.net.URL;
import javax.swing.ImageIcon;
public class Example {
public ImageIcon getImage() {
URL url = Example.class.getResource( "image.png" );
if( url != null ) {
return new ImageIcon( url );
}
return null; // TODO: Better error handling
}
}
The important part Example.class.getResource( "image.png" )
is that the path to the image is relative to the class name; in this case, it is located in the same directory as the class file. You can also use this line in any other class, leaving the link Example.class
intact.
source to share
Primarily.
Is Etc a package? In other words, at the top of your example file, you have
Etc package;
???
Usually, package names are lowercase, which is why I ask.
Second, while you can use relative paths to access resources, I would recommend always using absolute paths.
So
URL url = Example.class.getResource ("/Etc/image.png");
if Etc is a packet, otherwise
URL url = Example.class.getResource ("/image.png");
if it isn't.
source to share