{"id":981,"date":"2008-01-06T21:14:00","date_gmt":"2008-01-06T21:14:00","guid":{"rendered":"https:\/\/www.keenertech.com\/?p=981"},"modified":"2008-01-06T21:14:00","modified_gmt":"2008-01-06T21:14:00","slug":"reading-a-resource-from-a-jar-file","status":"publish","type":"post","link":"https:\/\/staging.keenertech.com\/?p=981","title":{"rendered":"Reading a Resource from a JAR File"},"content":{"rendered":"\n<p>There are times when it can be convenient for static files (such as text files, configuration files, images, etc.) to be packaged with a library. In the Java world, these types of files are referred to as resources and the libraries are known as jar files. The simplest way to ensure that a jar file can reference the resources it needs is to physically bundle them into the jar file itself.&nbsp;<\/p>\n\n\n\n<p>The question then becomes: How can the code within a jar file reference a resource file?<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Reading a Resource File<\/h3>\n\n\n\n<p>It&#8217;s actually pretty simple, as illustrated in&nbsp;<strong>Listing 1<\/strong>. Java provides several ways to read a resource file, of which the simplest is to use the getResourceAsStream method provided by Java&#8217;s Class class. This method accepts the name of the resource as a parameter and returns an InputStream reference for the resource (or null if it cannot find the resource). Content can be easily read from the file using a BufferedReader object.<\/p>\n\n\n\n<p>The name provided to the getResourceAsStream method can be an absolute or relative pathname. If relative, it is interpreted relative to the package path. For example:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\" colspan=\"2\">Type<\/td><td class=\"has-text-align-center\" data-align=\"center\">Path<\/td><td class=\"has-text-align-center\" data-align=\"center\">Expected&nbsp;Location<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">&nbsp;<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Absolute<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">\/myapp.properties<\/td><td class=\"has-text-align-center\" data-align=\"center\">\/myapp.properties<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">&nbsp;<\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>Relative<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">myapp.properties<\/td><td class=\"has-text-align-center\" data-align=\"center\">\/com\/keenertech\/experiment\/myapp.properties<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>The leading &#8220;\/&#8221; causes the getResourceAsStream method to look for the resource at the top level within the jar file. With the relative pathname, the file is expected to be located at the same level within the jar file as the class itself.<\/p>\n\n\n\n<p>Note that the ClassLoader class also has a getResourceAsStream method which can be used to read resources, but it only supports absolute paths. In general, the Class version of the method is more frequently used.<\/p>\n\n\n\n<p class=\"has-text-align-center\"><strong>Listing 1 &#8211; Displaying A Resource File<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">package com.keenertech.experiment;\n\nimport java.io.*;\nimport java.util.*;\n\npublic class ResourceExperiment\n{ \n   private void displayResource(String strName)\n   {\n      try\n      {\n         BufferedReader objBin = new BufferedReader(new InputStreamReader(\n            this.getClass().getResourceAsStream(strName)));\n         if (objBin != null)\n         {\n            String strLine = null;\n            while ((strLine = objBin.readLine()) != null)\n            {\n               System.out.println(strLine);\n            }\n            objBin.close();\n         }\n         else\n         {\n            System.out.println(\"Error:&nbsp;Unable to retrieve InputStream\");\n         }\n      }\n      catch (Exception e)\n      {\n         System.out.println(e);\n      }\n   } \/\/ End Method\n\n   public static void main(String[] args)\n   {\n      ResourceExperiment objRes = new ResourceExperiment();\n      objRes.displayResource(\"\/myapp.properties\");\n   } \/\/ End Method\n\n } \/\/ End Class\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Reading a Properties File<\/h3>\n\n\n\n<p>Well, that was a great way to read, and display, a resource file, but it would be nice to actually use the properties defined in the myapp.properties file.&nbsp;<strong>Listing 2<\/strong>&nbsp;shows how the properties can easily be processed from a configuration file packaged as a resource. This technique can be a great way to set default parameters for a class.<\/p>\n\n\n\n<p><strong>Listing 2 &#8211; Reading Properties From a Resource File<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"> private void readPropertyFile(String fileName)\n {\n    try\n    {\n       Properties objProperties = new Properties();\n       objProperties.load(this.getClass().getResourceAsStream(fileName));\n\n       strHostName = objProperties.getProperty(\"hostname\");\n       \/\/ .....more properties as needed.....\n    }\n    catch (Exception e)\n    {\n       System.out.println(\"ERROR: Could not read properties file\\n\");\n       e.printStackTrace();\n    }\n } \/\/ End Method\n<\/pre>\n\n\n\n<p>To read the properties from the file, create an instance of the Properties class, then call the object&#8217;s Load method with an InputStream that references the resource, as shown below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;objProperties.load(this.getClass().getResourceAsStream(fileName));<\/code><\/pre>\n\n\n\n<p>To get a value for an individual property:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&nbsp;&nbsp;&nbsp;strHostName = objProperties.getProperty(\"hostname\");<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>In Java, static resources can safely and effectively be bundled with compiled classes within easily distributable jar files. Storing such resources within the jar files ensures that the resources will be available to classes when needed, i.e. \u2014 it is very difficult for the resources to become separated from the code when they are bundled with it. In turn, resources can be easily referenced by Java code, so there&#8217;s no penalty, in terms of access cost, in bundling resources within jar files.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are times when it can be convenient for static files (such as text files, configuration files, images,<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[109,110],"class_list":["post-981","post","type-post","status-publish","format-standard","hentry","category-software","tag-jar","tag-java"],"_links":{"self":[{"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=\/wp\/v2\/posts\/981","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=981"}],"version-history":[{"count":0,"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=\/wp\/v2\/posts\/981\/revisions"}],"wp:attachment":[{"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=981"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=981"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/staging.keenertech.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=981"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}