{"id":510,"date":"2016-10-01T13:57:47","date_gmt":"2016-10-01T05:57:47","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=510"},"modified":"2018-09-04T23:50:33","modified_gmt":"2018-09-04T15:50:33","slug":"how-to-manually-create-the-jar-file-for-running-your-java-application","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-manually-create-the-jar-file-for-running-your-java-application\/","title":{"rendered":"How to manually create the jar file for running your Java application"},"content":{"rendered":"<p>Advances in software engineering had shortened the time needed to build an application from scratch. For instance with <a href=\"https:\/\/projects.spring.io\/spring-boot\/\" title=\"Spring Boot home page\" target=\"_blank\">Spring Boot<\/a>, I can easily build my own web API backed by a web server of my choice into a single jar file. By running that jar file, I can start a process that responds to HTTP requests directed at my customized endpoints.<\/p>\n<p>However, not knowing how that jar file is formed and read by the Java Virtual Machine can cloud our understanding of application development with Java. To help understand Java application development better, I described how to manually create a jar file for running a Java application.<\/p>\n<h2>Defining a sample scenario<\/h2>\n<p>As the topic of this post is to document the process of manually preparing an executable jar file, I shall                       define a simple scenario for my Java application. <\/p>\n<p>Let's suppose that I want to build a Java application that downloads Techcoil's robots.txt and saves it in the same directory where my Java application resides in. <\/p>\n<p>To fulfil this requirement, I refer to my previous post on <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-send-http-get-request-with-java-without-using-any-external-libraries\/\" title=\"How to send HTTP GET request with Java without using any external libraries\" target=\"_blank\">how to send HTTP GET request with Java without using any external libraries<\/a> to derive the following Java source file:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nimport java.io.ByteArrayOutputStream;\r\nimport java.io.IOException;\r\nimport java.io.PrintWriter;\r\nimport java.net.HttpURLConnection;\r\nimport java.net.URL;\r\nimport java.util.Scanner;\r\n\r\npublic class TechcoilRobotTxtDownloader {\r\n\r\n\tpublic static void main(String&#x5B;] args) {\r\n\t\t\r\n\t\tByteArrayOutputStream responseBodyBaos = null;\r\n                Scanner httpResponseBodyScanner = null;\r\n                try {\r\n                    \/\/ Define server endpoint\r\n                    URL robotsUrl = new URL(&quot;http:\/\/www.techcoil.com\/robots.txt&quot;);\r\n                    HttpURLConnection urlConnection = (HttpURLConnection) robotsUrl.openConnection(); \r\n \r\n                    httpResponseBodyScanner = new Scanner(urlConnection.getInputStream());\r\n \r\n                    \/\/ Use a ByteArrayOutputStream to store the contents of the HTTP response body\r\n                    responseBodyBaos = new ByteArrayOutputStream();\r\n                    while(httpResponseBodyScanner.hasNextLine()) {\r\n                        responseBodyBaos.write(httpResponseBodyScanner.nextLine().getBytes());\r\n                    }\r\n                    responseBodyBaos.close();\r\n                    httpResponseBodyScanner.close();\r\n \r\n                    \/\/ Verify contents of robots.txt\r\n                    String robotsContent = responseBodyBaos.toString();\r\n                    if (robotsContent.trim().equals(&quot;Sitemap: http:\/\/www.techcoil.com\/sitemap-index.xml&quot;)) {\r\n                        System.out.println(&quot;Able to retrieve robots.txt from server. Server is running fine.&quot;);\r\n                \r\n                        \/\/ Save the robots content to file in the same directory\r\n                        PrintWriter printWriter = new PrintWriter(&quot;techcoil-robot.txt&quot;);\r\n                        printWriter.println(robotsContent);\r\n                        printWriter.flush();\r\n                        printWriter.close();\r\n                \r\n                    }\r\n                    else {\r\n                        System.out.println(&quot;Not able to retrive robots.txt from server.&quot;);\r\n                    }\r\n \r\n                } catch(IOException ioException) {\r\n                    System.out.println(&quot;IOException occurred while contacting server.&quot;);\r\n                    ioException.printStackTrace();\r\n                } finally {\r\n                    if (responseBodyBaos != null) {\r\n            \t        try {\r\n                                responseBodyBaos.close();\r\n            \t        } catch (IOException ioe) {\r\n            \t\t        System.out.println(&quot;Error while closing response body stream&quot;);\r\n            \t        }\r\n                    }\r\n                    if (httpResponseBodyScanner != null) {\r\n                        httpResponseBodyScanner.close();\r\n                    }\r\n                }\r\n\r\n\t}\r\n\r\n}\r\n<\/pre>\n<p>I added the block that utilized an instance of java.io.PrintWriter to write the contents of Techcoil's robots.txt. With that, I had created an Java application that can be run by the Java Virtual Machine. <\/p>\n<h2>Running your Java application that is not contained in a jar file<\/h2>\n<p>To get a runnable Java application, we will first need to get the Java Compiler to compile <code>TechcoilRobotTxtDownloader.java<\/code>:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\njavac TechcoilRobotTxtDownloader.java\r\n<\/pre>\n<p>Once the Java compiler completed its job, we will get <code>TechcoilRobotTxtDownloader.class<\/code> in the same directory where <code>TechcoilRobotTxtDownloader.java<\/code> is located at. <code>TechcoilRobotTxtDownloader.class<\/code> is our runnable Java application.<\/p>\n<p>To run our Java application, we will then run the following command:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\njava TechcoilRobotTxtDownloader\r\n<\/pre>\n<p>Noticed that we do not specify the <code>.class<\/code> extension in the input parameter to our <code>java<\/code> executable. This will tell the Java Virtual Machine to look inside of <code>TechcoilRobotTxtDownloader.class<\/code> and run the static <code>main<\/code> method. <\/p>\n<p>So in short, we will need to provide the Java Virtual Machine with a .class file that contains a static <code>main<\/code> method that contains the codes that will do what we wanted to do.<\/p>\n<h2>Understanding how the Java Virtual Machine run your Java application which is contained in a jar file<\/h2>\n<p>Before going into the command to prepare the jar file, it is beneficial to understand how the Java Virtual Machine runs your Java application.<\/p>\n<p>By passing the name of the class (TechcoilRobotTxtDownloader) to the <code>java<\/code> executable, the <code>java<\/code> executable will be able to understand that there is a <code>TechcoilRobotTxtDownloader.class<\/code> that it can find in the current directory. That is straightforward.<\/p>\n<p>In the case where our Java application is contained within a jar file, we have to make sure that our jar file contains a minimal file structure as follows:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nnameOfJar.jar\r\n|-- TechcoilRobotTxtDownloader.class\r\n|-- META-INF\r\n|   |-- MANIFEST.MF\r\n<\/pre>\n<p>With that, whenever the <code>java<\/code> executable receives a <code>.jar<\/code> file, it will look into the <code>META-INF<\/code> directory inside the .jar file for a <code>MANIFEST.MF<\/code> file. The <code>MANIFEST.MF<\/code> will need to contain a directive to tell <code>java<\/code> executable where to find the class that contains a static <code>main<\/code> method to run. The <code>META-INF<\/code> directory and <code>MANIFEST.MF<\/code> file have to named as such, they cannot be give other names.<\/p>\n<h2>Creating the manifest file that tells the java executable where to find the class that contains the static main method<\/h2>\n<p>To create a manifest file that tells the java executable where to find the class that contains the static main method, I run the following command in my shell, inside of the directory that contains <code>TechcoilRobotTxtDownloader.class<\/code>:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nnano MANIFEST.MF\r\n<\/pre>\n<p>I then added the following line:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nMain-Class: TechcoilRobotTxtDownloader\r\n<\/pre>\n<p>and saved the changes.<\/p>\n<p>The <code>Main-Class<\/code> directive tells the java executable to find <code>TechcoilRobotTxtDownloader.class<\/code>, which contains the static <code>main<\/code> method, in the same directory as the <code>META-INF<\/code> directory. With this information, the java executable will then be able to know that I want to run <code>TechcoilRobotTxtDownloader.class<\/code> that is contained within the jar file.<\/p>\n<h2>Creating the executable jar file for running your Java application<\/h2>\n<p>After I had created <code>MANIFEST.MF<\/code>, I then continued on to create the jar file. The JDK contains the <code>jar<\/code> executable for us create jar files.<\/p>\n<p>To create the jar file, I run the following command in my terminal:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\njar cvfm TechcoilRobotTxtDownloader.jar MANIFEST.MF TechcoilRobotTxtDownloader.class\r\n<\/pre>\n<p>The first input parameter contains four instructions for the <code>jar<\/code> executable:<\/p>\n<ul>\n<li><strong>c<\/strong> for indicating that I want to create a jar file.<\/li>\n<li><strong>v<\/strong> for indicating that I want the jar executable to report its progress to me.<\/li>\n<li><strong>f<\/strong> for indicating that I wish to name my jar file myself.<\/li>\n<li><strong>m<\/strong> for indicating that I want to provide my own manifest file.<\/li>\n<\/ul>\n<p>With that, the jar executable will read <code>TechcoilRobotTxtDownloader.jar<\/code> as the name for the <code>jar<\/code> file, <code>MANIFEST.MF<\/code> as the manifest file to include inside the META-INF directory inside of the <code>jar<\/code> file and anything that comes afterwards will be included in the root of the jar file.<\/p>\n<p>With that command, I will get the following output:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nadded manifest\r\nadding: TechcoilRobotTxtDownloader.class(in = 2539) (out= 1437)(deflated 43%)\r\n<\/pre>\n<p>This told me that the <code>jar<\/code> executable was able to find <code>MANIFEST.MF<\/code> and <code>TechcoilRobotTxtDownloader.class<\/code>, placing them inside the appropriate locations within the newly created <code>jar<\/code> file.<\/p>\n<p>As an aside, in this case the manifest file that we provided for the <code>jar<\/code> executable can be give other names. This is because the <code>jar<\/code> executable will make sure that the manifest file is named as <code>MANIFEST.MF<\/code> before putting it into the <code>META-INF<\/code> directory.<\/p>\n<h2>Running the jar file that contains our Java application<\/h2>\n<h3>Running the jar file from command line<\/h3>\n<p>To run the jar file that contains our Java application, I run the following command in my terminal:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\njava -jar TechcoilRobotTxtDownloader.jar\r\n<\/pre>\n<p>The <code>-jar<\/code> flags tells the java executable that we are providing it a jar file that contains the Java application with a static <code>main<\/code> method. When the command completes, I will see the output in my shell:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\nAble to retrieve robots.txt from server. Server is running fine.\r\n<\/pre>\n<p>and <code>techcoil-robot.txt<\/code> in the same directory where <code>TechcoilRobotTxtDownloader.jar<\/code> resides in.<\/p>\n<h3>Running the jar file from GUI based operating system<\/h3>\n<p>In a GUI based operating system, if the default application for opening .jar files is set as the Java Launcher, I will also be able to run <code>TechcoilRobotTxtDownloader.jar<\/code> by double-clicking on the <code>TechcoilRobotTxtDownloader.jar<\/code> icon.<\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-8e\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-8e&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-8e&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F510&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>Advances in software engineering had shortened the time needed to build an application from scratch. For instance with <a href=\"https:\/\/projects.spring.io\/spring-boot\/\" title=\"Spring Boot home page\" target=\"_blank\">Spring Boot<\/a>, I can easily build my own web API backed by a web server of my choice into a single jar file. By running that jar file, I can start a process that responds to HTTP requests directed at my customized endpoints.<\/p>\n<p>However, not knowing how that jar file is formed and read by the Java Virtual Machine can cloud our understanding of application development with Java. To help understand Java application development better, I described how to manually create a jar file for running a Java application.<\/p>\n","protected":false},"author":1,"featured_media":1220,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":true,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[316,315,6,317,195],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Java-logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-8e","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/510"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=510"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/510\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1220"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=510"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=510"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=510"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}