Get a resource using getResource()
TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
- leading slash to denote the root of the classpath
- slashes instead of dots in the path
- you can call
getResource()
directly on the class.
how to load a resource using Class.getResource()?
If you want to load a Resource, you should put them in src/main/resources
, as they'd be ignored in src/main/java
How should I use getResource() in Java?
String clipName = "Chook.wav";
When using getResource
, the string you pass in must be either an absolute name or be valid relative to a certain class. Since you're using ClassLoader.getResource()
and not Class.getResource()
, it must be an absolute path.
Without seeing your actual file hierarchy, I can only guess that "bin" is the root of your compiled classes and resources, and "ibm1260" is a package/folder within that path, and "Chook.wav" exists in that folder. If that's the case, then you need to use /ibm1260/Chook.wav
(or potentially ibm1260/Chook.wav
, I don't typically use the class loader for resource lookups) as the name of the file that you pass in to getResource()
.
Either way, you need to make sure that the file is copied into the location of your compiled code and that the root folder is on the classpath.
Unable to get resources using getResource()
Try something like this for setting the image icon
ImageIcon imageIcon = new ImageIcon(getClass().getResource("myImage.png"));
Your image file should be located within the src folder if your using an IDE. If your not using an IDE , put the image in the same folder as your .java files.
Unable to find file (getResource)
Try this; Note that leading "/" is removed from file path.
public boolean isDatabaseFileExist(){
return this.getClass().getClassLoader().getResource("remotecontrolserverfx/databases/user_config.db")!=null;
}
If you want to get the File
object;
File databaseFile = new File(this.getClass().getClassLoader().getResource("remotecontrolserverfx/databases/user_config.db").getFile());
Related Topics
Implementing Two Interfaces in a Class with Same Method. Which Interface Method Is Overridden
"Code Too Large" Compilation Error in Java
Java Code for Calculating Leap Year
In What Order Do Static/Instance Initializer Blocks in Java Run
How to Convert Comma-Separated String to List
Is There a "Word Wrap" Property for Jlabel
Java Array, Finding Duplicates
How to Check If the User Is Pressing a Key
How to Map an Entity Field Whose Name Is a Reserved Word in JPA
Using Regex to Generate Strings Rather Than Match Them