How To Charge Resources From Classpath Inwards Coffee Alongside Example

Classpath inward Java is non entirely used to charge .class files, but too tin live used to charge resources e.g. properties file, images, icons, thumbnails, or whatever binary content. Java provides API to read these resources equally InputStream or URL. Suppose, yous receive got a properties file within config folder of your project, as well as yous desire to charge that properties file, how create yous create that? Similarly, yous receive got icons as well as thumbnails for your spider web applications on icons directory of your project, how create yous charge them? Answer is yesteryear using java.lang.Class' getResource() as well as getResourceAsStream() method. These method accepts path of resources equally String as well as returns URL as well as InputStream respectively. You tin obtain a reference of Class yesteryear calling either getClass() method or yesteryear using class literal. If yous receive got an object, thence yous tin telephone telephone getClass() because its a non-static method, on the other hand, if yous don't receive got whatever object, yous tin exactly operate .class alongside lift of whatever shape e.g. Sample.class volition give yous reference of java.lang.Class. These methods are available from JDK 1.1 as well as yous tin fifty-fifty operate them anywhere yous receive got access to amount Java library. If yous are creating J2ME games or application, yous tin operate these method to charge icons as well as tiles for your game, as well as all other resources for your application equally well.


How does getResourceAsStream works

Internally this method delegate the loading asking of resources to its shape loader. If yous telephone telephone getResourceAsStream() method on an object which is loaded yesteryear BootStrap ClassLoader thence it volition delegate it to ClassLoader.getSystemResourceAsStream(java.lang.String) method.

We overstep path of resources to this method but rules for searching resources associated alongside a given shape are implemented yesteryear the defining shape loader of the class.


Since yous tin overstep both absolute as well as relative path to Class.getResourceAsStream(), but ClassLoader.getResourceAsStream() takes an absolute path, that's why an absolute resources lift is constructed from the given resources lift using next algorithm :
If the lift begins alongside a '/' ('\u002f'), thence the absolute lift of the resources is the part of the lift next the '/'. Otherwise, the absolute lift is of the next form:
modified_package_name/name where the modified_package_name is the parcel lift of this object with '/' substituted for '.' ('\u002e').

This means, the resources lift passed to the method should hold off similar /com/abc/config/app.properties if the app.properties is stored inward the com.abc.config parcel instead of the electrical flow class's.

If yous hold off at the code of java.lang.Class inward Eclipse IDE yesteryear using short-cut Ctrl+T as well as typing java.lang.Class, yous tin encounter how this method plant :

 public InputStream getResourceAsStream(String name) {
        lift = resolveName(name);         ClassLoader cl = getClassLoader0();         if (cl==null) {             // H5N1 arrangement class.             return ClassLoader.getSystemResourceAsStream(name);         }         return cl.getResourceAsStream(name); }

This algorithm is implemented at resolveName() method, equally seen below :

    /**
     * Add a parcel lift prefix if the lift is non absolute Remove leading "/"      * if lift is absolute      */     private String resolveName(String name) {         if (name == null) {             return name;         }         if (!name.startsWith("/")) {             Class c = this;             while (c.isArray()) {                 c = c.getComponentType();             }             String baseName = c.getName();             int index = baseName.lastIndexOf('.');             if (index != -1) {                 lift = baseName.substring(0, index).replace('.', '/')                     +"/"+name;             }         } else {             lift = name.substring(1);         }         return name;     }

 Classpath inward Java is non entirely used to charge  How to Load Resources from Classpath inward Java alongside Example
Main work comes piece loading resources using getResourceAsStream() method is NullPointerException, because this method render null if its non able to uncovering the resource. In next example, nosotros receive got a Eclipse project, as well as I receive got created a properties file called app.properties within config directory. Now to charge that file, I exactly require to overstep "app.properties", if I overstep anything similar "config/app.properties" or "/config/app.properties" getResourceAsStream() volition render null, as well as code volition afterwards throw NullPointerException equally shown below :

Exception inward thread "main" java.lang.NullPointerException     at java.util.Properties$LineReader.readLine(Unknown Source)     at java.util.Properties.load0(Unknown Source)     at java.util.Properties.load(Unknown Source)     at Test.main(Test.java:29)

to avoid this fault yous must banking venture fit output of getResourceAsStream() earlier using it, defensive programming is in that location exactly because of this form of methods.


Java Program to charge Resource from Classpath

Here is our consummate Java plan to charge images, resources, text file or binary file from classpath inward Java, resources tin live anything, what is of import is that it must live accessible.

package test;  import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties;  /**  * Java Program to demonstrate how to charge resources e.g. properties file from  * classpath. There are ii ways to charge resources inward Java, 1 yesteryear using  * getResourceAsStream() as well as getResource() method from java.lang.Class. Main  * departure betwixt these ii methods are that 1 returns an InputStream  * piece other returns a URL object.  *  * @author Javin Paul  */ public class ResourceLoader{      public static void main(String args[]) {          // loading resources using getResourceAsStream() method         InputStream inward = ResourceLoader.class.getResourceAsStream("app.properties");          Properties config = new Properties();         try {             config.load(in);             System.out.println(config.getProperty("name"));             System.out.println(config.getProperty("version"));          } catch (IOException e1) {             e1.printStackTrace();         }          // loading resources using getResource() method         URL resourceURL = Test.class.getResource("app.properties");         Properties appConfig = new Properties();         try {             appConfig.load(resourceURL.openStream());             System.out.println(appConfig.getProperty("name"));             System.out.println(appConfig.getProperty("version"));          } catch (IOException e) {             e.printStackTrace();         }      }  }  Output: SampleApp 1.0.0 SampleApp 1.0.0

If yous hold off closely yous volition uncovering that nosotros receive got used both getResource() as well as getResourceAsStream() method to charge resources from classpath inward Java, inward this illustration exactly properties file. First illustration looks to a greater extent than cleaner than minute illustration because nosotros don't require to opened upwards an explicit stream, getResourceAsStream() method returns an InputStream, which tin live used anywhere. That's all on how to charge resources from class-path inward Java. 

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Komentar

Postingan populer dari blog ini

2 Ways To Banking Concern Tally If A String Is Rotation Of Other Inward Java?

How To Convert String To Integer To String Inward Coffee Amongst Example

How To Induce Chrome, Firefox Blurry, Over Bright, Fading Afterwards Windows Ten Update