How To Charge Resources From Classpath Inward Coffee Alongside 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 whatever binary content. Java provides API to read these resources every bit InputStream or URL. Suppose, y'all receive got a properties file within config folder of your project, together with y'all desire to charge that properties file, how create y'all create that? Similarly, y'all receive got icons together with thumbnails for your spider web applications on icons directory of your project, how create y'all charge them? Answer is past times using java.lang.Class' getResource() together with getResourceAsStream() method. These method accepts path of resources every bit String together with returns URL together with InputStream respectively. You tin obtain a reference of Class past times calling either getClass() method or past times using class literal. If y'all receive got an object, together with thence y'all tin telephone vociferation upwards getClass() because its a non-static method, on the other hand, if y'all don't receive got whatever object, y'all tin but purpose .class amongst lift of whatever flat e.g. Sample.class volition give y'all reference of java.lang.Class. These methods are available from JDK 1.1 together with y'all tin fifty-fifty purpose them anywhere y'all receive got access to marrow Java library. If y'all are creating J2ME games or application, y'all tin purpose these method to charge icons together with tiles for your game, together with 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 y'all telephone vociferation upwards getResourceAsStream() method on an object which is loaded past times BootStrap ClassLoader together with 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 amongst a given flat are implemented past times the defining flat loader of the class.


Since y'all tin overstep both absolute together with 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 amongst a '/' ('\u002f'), together with thence the absolute lift of the resources is the component subdivision 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 bundle 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 bundle instead of the electrical flow class's.

If y'all hold off at the code of java.lang.Class inward Eclipse IDE past times using short-cut Ctrl+T together with typing java.lang.Class, y'all tin run into how this method plant :

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

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

    /**
     * Add a bundle 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 exclusively used to charge  How to Load Resources from Classpath inward Java amongst Example
Main work comes piece loading resources using getResourceAsStream() method is NullPointerException, because this method render zippo if its non able to discovery the resource. In next example, nosotros receive got a Eclipse project, together with I receive got created a properties file called app.properties within config directory. Now to charge that file, I exactly need to overstep "app.properties", if I overstep anything similar "config/app.properties" or "/config/app.properties" getResourceAsStream() volition render null, together with 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 mistake y'all must banking concern 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 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 past times using  * getResourceAsStream() together with 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 y'all hold off closely y'all volition discovery that nosotros receive got used both getResource() together with getResourceAsStream() method to charge resources from classpath inward Java, inward this instance exactly properties file. First instance looks to a greater extent than cleaner than instant instance because nosotros don't need 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!


Sumber https://javarevisited.blogspot.com/

0 Response to "How To Charge Resources From Classpath Inward Coffee Alongside Example"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel