How To Charge Resources From Classpath Inwards Coffee Alongside Example

Advertisement

Masukkan script iklan 970x90px

How To Charge Resources From Classpath Inwards Coffee Alongside Example

Sabtu, 06 Februari 2021

Classpath inwards Java is non exclusively used to charge .class files, but every bit good tin live used to charge resources e.g. properties file, images, icons, thumbnails, or whatever binary content. Java provides API to read these resources every bit InputStream or URL. Suppose, yous receive got a properties file within config folder of your project, in addition to yous desire to charge that properties file, how produce yous produce that? Similarly, yous receive got icons in addition to thumbnails for your spider web applications on icons directory of your project, how produce yous charge them? Answer is past times using java.lang.Class' getResource() in addition to getResourceAsStream() method. These method accepts path of resources every bit String in addition to returns URL in addition to InputStream respectively. You tin obtain a reference of Class past times calling either getClass() method or past times 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 purpose .class alongside mention of whatever flat e.g. Sample.class volition give yous reference of java.lang.Class. These methods are available from JDK 1.1 in addition to yous tin fifty-fifty purpose them anywhere yous receive got access to kernel Java library. If yous are creating J2ME games or application, yous tin purpose these method to charge icons in addition to tiles for your game, in addition to all other resources for your application every bit well.


How does getResourceAsStream works

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

We move past times path of resources to this method but rules for searching resources associated alongside a given flat are implemented past times the defining flat loader of the class.


Since yous tin move past times both absolute in addition to relative path to Class.getResourceAsStream(), but ClassLoader.getResourceAsStream() takes an absolute path, that's why an absolute resources mention is constructed from the given resources mention using next algorithm :
If the mention begins alongside a '/' ('\u002f'), thence the absolute mention of the resources is the component division of the mention next the '/'. Otherwise, the absolute mention is of the next form:
modified_package_name/name where the modified_package_name is the packet mention of this object with '/' substituted for '.' ('\u002e').

This means, the resources mention passed to the method should expect similar /com/abc/config/app.properties if the app.properties is stored inwards the com.abc.config packet instead of the electrical flow class's.

If yous expect at the code of java.lang.Class inwards Eclipse IDE past times using short-cut Ctrl+T in addition to typing java.lang.Class, yous tin come across how this method industrial plant :

 public InputStream getResourceAsStream(String name) {
        mention = resolveName(name);         ClassLoader cl = getClassLoader0();         if (cl==null) {             // Influenza A virus subtype H5N1 organization class.             return ClassLoader.getSystemResourceAsStream(name);         }         return cl.getResourceAsStream(name); }

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

    /**
     * Add a packet mention prefix if the mention is non absolute Remove leading "/"      * if mention 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) {                 mention = baseName.substring(0, index).replace('.', '/')                     +"/"+name;             }         } else {             mention = name.substring(1);         }         return name;     }

 Classpath inwards Java is non exclusively used to charge  How to Load Resources from Classpath inwards Java alongside Example
Main work comes land loading resources using getResourceAsStream() method is NullPointerException, because this method render nix if its non able to uncovering the resource. In next example, nosotros receive got a Eclipse project, in addition to I receive got created a properties file called app.properties within config directory. Now to charge that file, I exactly quest to move past times "app.properties", if I move past times anything similar "config/app.properties" or "/config/app.properties" getResourceAsStream() volition render null, in addition to code volition afterward throw NullPointerException every bit shown below :

Exception inwards 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 mistake yous must banking enterprise stand upwards for output of getResourceAsStream() earlier using it, defensive programming is in that location exactly because of this sort of methods.


Java Program to charge Resource from Classpath

Here is our consummate Java programme to charge images, resources, text file or binary file from classpath inwards 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 2 ways to charge resources inwards Java, 1 past times using  * getResourceAsStream() in addition to getResource() method from java.lang.Class. Main  * divergence betwixt these 2 methods are that 1 returns an InputStream  * land other returns a URL object.  *  * @author Javin Paul  */ public class ResourceLoader{      public static void main(String args[]) {          // loading resources using getResourceAsStream() method         InputStream inwards = 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 expect closely yous volition uncovering that nosotros receive got used both getResource() in addition to getResourceAsStream() method to charge resources from classpath inwards Java, inwards this instance exactly properties file. First instance looks to a greater extent than cleaner than minute instance because nosotros don't quest 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 inwards Java. 

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