Loading Resources Using Getclass().Getresource()

Loading resources using getClass().getResource()

You can request a path in this format:

/package/path/to/the/resource.ext

Even the bytes for creating the classes in memory are found this way:

my.Class -> /my/Class.class

and getResource will give you a URL which can be used to retrieve an InputStream.

But... I'd recommend using directly getClass().getResourceAsStream(...) with the same argument, because it returns directly the InputStream and don't have to worry about creating a (probably complex) URL object that has to know how to create the InputStream.

In short: try using getResourceAsStream and some constructor of ImageIcon that uses an InputStream as an argument.

Classloaders

Be careful if your app has many classloaders. If you have a simple standalone application (no servers or complex things) you shouldn't worry. I don't think it's the case provided ImageIcon was capable of finding it.

Edit: classpath

getResource is—as mattb says—for loading resources from the classpath (from your .jar or classpath directory). If you are bundling an app it's nice to have altogether, so you could include the icon file inside the jar of your app and obtain it this way.

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

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.

class.getResource().getFile() fetches older version of a file

getClass().getResource() loads resources from the classpath, not from filesystem. Class loaders are responsible for loading Java classes and resources during runtime dynamically to the JVM (Java Virtual Machine).

I would suggest using ClassLoader.getSystemResource():

    File testFile = new File(ClassLoader.getSystemResource("namr_two").getFile());

or:

    Class class1 = null;
try {
class1 = Class.forName("class1");
ClassLoader cl = class1.getClassLoader();
File testFile = new File(cl.getResource("namr_two").getFile());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

What does getClass().getResource(...) do when creating ImageIcon?

getClass().getResource(path)

locates the icon on the classpath and gives back the URL to use to load it. This is different from what you suggest to use. The constructor that takes only String loads the icon from the filesystem. It is done via getClass().getResource(path) so that you can package your icon and all resources your application needs within your distribution jar and still find and load it. Otherwise you'd have to rely on some path on the filesystem and make sure they exist where you expect them so that you can work with relative paths.



Related Topics



Leave a reply



Submit