How To Charge Resources From Classpath Inwards Coffee Amongst Example
Classpath inwards Java is non alone used to charge .class files, but equally good tin live used to charge resources e.g. properties file, images, icons, thumbnails, or whatsoever binary content. Java provides API to read these resources equally InputStream or URL. Suppose, you lot receive got a properties file within config folder of your project, as well as you lot desire to charge that properties file, how produce you lot produce that? Similarly, you lot receive got icons as well as thumbnails for your spider web applications on icons directory of your project, how produce you lot charge them? Answer is past times 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 past times calling either getClass() method or past times using class literal. If you lot receive got an object, as well as then you lot tin telephone telephone getClass() because its a non-static method, on the other hand, if you lot don't receive got whatsoever object, you lot tin merely role .class amongst elevate of whatsoever shape e.g. Sample.class volition give you lot reference of java.lang.Class. These methods are available from JDK 1.1 as well as you lot tin fifty-fifty role them anywhere you lot receive got access to marrow Java library. If you lot are creating J2ME games or application, you lot tin role these method to charge icons as well as tiles for your game, as well as all other resources for your application equally well.
We overstep path of resources to this method but rules for searching resources associated amongst a given shape are implemented past times the defining shape loader of the class.
Since you lot 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 elevate is constructed from the given resources elevate using next algorithm :
This means, the resources elevate passed to the method should hold off 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 you lot hold off at the code of java.lang.Class inwards Eclipse IDE past times using short-cut Ctrl+T as well as typing java.lang.Class, you lot tin meet how this method industrial plant :
public InputStream getResourceAsStream(String name) {
This algorithm is implemented at resolveName() method, equally seen below :
/**
Main work comes piece loading resources using getResourceAsStream() method is NullPointerException, because this method render nothing if its non able to detect 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 bespeak 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 afterward throw NullPointerException equally shown below :
to avoid this fault you lot must banking enterprise jibe output of getResourceAsStream() earlier using it, defensive programming is at that topographic point exactly because of this variety of methods.
If you lot hold off closely you lot volition detect that nosotros receive got used both getResource() as well as getResourceAsStream() method to charge resources from classpath inwards Java, inwards this instance exactly properties file. First illustration looks to a greater extent than cleaner than minute illustration because nosotros don't bespeak 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!
How does getResourceAsStream works
Internally this method delegate the loading asking of resources to its shape loader. If you lot telephone telephone getResourceAsStream() method on an object which is loaded past times BootStrap ClassLoader as well as then 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 shape are implemented past times the defining shape loader of the class.
Since you lot 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 elevate is constructed from the given resources elevate using next algorithm :
If the elevate begins amongst a '/' ('\u002f'), as well as then the absolute elevate of the resources is the constituent of the elevate next the '/'. Otherwise, the absolute elevate is of the next form:
modified_package_name/name where the modified_package_name is the packet elevate of this object with '/' substituted for '.' ('\u002e').
This means, the resources elevate passed to the method should hold off 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 you lot hold off at the code of java.lang.Class inwards Eclipse IDE past times using short-cut Ctrl+T as well as typing java.lang.Class, you lot tin meet how this method industrial plant :
public InputStream getResourceAsStream(String name) {
elevate = 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 packet elevate prefix if the elevate is non absolute Remove leading "/" * if elevate 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) { elevate = baseName.substring(0, index).replace('.', '/') +"/"+name; } } else { elevate = name.substring(1); } return name; }
Main work comes piece loading resources using getResourceAsStream() method is NullPointerException, because this method render nothing if its non able to detect 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 bespeak 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 afterward throw NullPointerException equally 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 fault you lot must banking enterprise jibe output of getResourceAsStream() earlier using it, defensive programming is at that topographic point exactly because of this variety 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 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, ane past times using * getResourceAsStream() as well as getResource() method from java.lang.Class. Main * deviation betwixt these 2 methods are that ane 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 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 you lot hold off closely you lot volition detect that nosotros receive got used both getResource() as well as getResourceAsStream() method to charge resources from classpath inwards Java, inwards this instance exactly properties file. First illustration looks to a greater extent than cleaner than minute illustration because nosotros don't bespeak 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!
0 Response to "How To Charge Resources From Classpath Inwards Coffee Amongst Example"
Post a Comment