How To Charge Resources From Classpath Inwards Coffee Amongst Example

Classpath inward Java is non exclusively used to charge .class files, but too tin live used to charge resources e.g. properties file, images, icons, thumbnails, or whatsoever binary content. Java provides API to read these resources every bit InputStream or URL. Suppose, you lot take away maintain a properties file within config folder of your project, in addition to you lot desire to charge that properties file, how create you lot create that? Similarly, you lot take away maintain icons in addition to thumbnails for your spider web applications on icons directory of your project, how create you lot charge them? Answer is yesteryear 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 yesteryear calling either getClass() method or yesteryear using class literal. If you lot take away maintain an object, in addition to thus you lot tin telephone band getClass() because its a non-static method, on the other hand, if you lot don't take away maintain whatsoever object, you lot tin exactly purpose .class amongst get upwards of whatsoever shape e.g. Sample.class volition give you lot reference of java.lang.Class. These methods are available from JDK 1.1 in addition to you lot tin fifty-fifty purpose them anywhere you lot take away maintain access to amount Java library. If you lot are creating J2ME games or application, you lot 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 shape loader. If you lot telephone band getResourceAsStream() method on an object which is loaded yesteryear BootStrap ClassLoader in addition to thus it volition delegate it to ClassLoader.getSystemResourceAsStream(java.lang.String) method.

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


Since you lot tin exceed both absolute in addition to relative path to Class.getResourceAsStream(), but ClassLoader.getResourceAsStream() takes an absolute path, that's why an absolute resources get upwards is constructed from the given resources get upwards using next algorithm :
If the get upwards begins amongst a '/' ('\u002f'), in addition to thus the absolute get upwards of the resources is the component of the get upwards next the '/'. Otherwise, the absolute get upwards is of the next form:
modified_package_name/name where the modified_package_name is the packet get upwards of this object with '/' substituted for '.' ('\u002e').

This means, the resources get upwards passed to the method should await similar /com/abc/config/app.properties if the app.properties is stored inward the com.abc.config packet instead of the electrical current class's.

If you lot await at the code of java.lang.Class inward Eclipse IDE yesteryear using short-cut Ctrl+T in addition to typing java.lang.Class, you lot tin come across how this method industrial plant :

 public InputStream getResourceAsStream(String name) {
        get upwards = 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, every bit seen below :

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

 Classpath inward Java is non exclusively used to charge  How to Load Resources from Classpath inward Java amongst Example
Main occupation comes piece loading resources using getResourceAsStream() method is NullPointerException, because this method render nil if its non able to observe the resource. In next example, nosotros take away maintain a Eclipse project, in addition to I take away maintain created a properties file called app.properties within config directory. Now to charge that file, I exactly take away to exceed "app.properties", if I exceed 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 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 you lot must depository fiscal establishment tally output of getResourceAsStream() earlier using it, defensive programming is at that spot exactly because of this variety 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 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 2 ways to charge resources inward Java, 1 yesteryear using  * getResourceAsStream() in addition to getResource() method from java.lang.Class. Main  * divergence betwixt these 2 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 you lot await closely you lot volition observe that nosotros take away maintain used both getResource() in addition to getResourceAsStream() method to charge resources from classpath inward Java, inward this instance exactly properties file. First illustration looks to a greater extent than cleaner than minute illustration because nosotros don't take away 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!

Belum ada Komentar untuk "How To Charge Resources From Classpath Inwards Coffee Amongst Example"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel