JAR
The Java Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications.
Get Resource from JAR
Use java.lang.Class class's method : getResource() and getResourceAsStream() - The simplest way to retrieve a resource from JAR file.
- URL getResource(String name) - Finds a resource with a given name.
- InputStream getResourceAsStream(String name) - Finds a resource with a given name.
EXAMPLE – Source code
This example demonstrate how to read an XML file which is packed into the JAR. This is a java-console application.
XML File Std.xml |
<?xml version="1.0" ?> <Students> <Std ClassName="1st"> <Roll>10</Roll> <Name>Mr. Raj</Name> </Std> <Std ClassName="3rd"> <Roll>11</Roll> <Name>Mr. Rohan</Name> </Std> </Students> |
JAVA source code ReadStd.java |
import org.w3c.dom.*; import javax.xml.parsers.*; import java.io.*;
public class ReadStd { public static void main(String []args) throws Exception { // Read Resource InputStream ii=ReadStd.class.getResourceAsStream("Std.xml");
DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance(); DocumentBuilder build=fact.newDocumentBuilder(); Document doc=build.parse(ii);
Element root=doc.getDocumentElement(); System.out.println(root.getTagName());
NodeList list=root.getChildNodes(); System.out.println("Total Nodes : " + list.getLength());
int i;
for(i=0;i<list.getLength();i++) { Node t=list.item(i); if(t.hasAttributes()) System.out.print("Node has an attribute"); System.out.println(t.getNodeName() + " " + t.getNodeType() + " " + t.getNodeValue()); if(t.hasChildNodes()) { NodeList p=t.getChildNodes(); for(int j=0;j<p.getLength();j++) { Node t1=p.item(j); System.out.println(t1.getNodeName() + " " + t1.getNodeType() + " " + t1.getNodeValue()); } } } } } |
MANIFEST File m.mf |
Main-Class: ReadStd |
NOTE: All three files namely Std.xml, ReadStd.xml and m.mf must be reside in the same directory/folder. |
COMPILE & PACKAGE
> javac ReadStd.java
> jar –cvfm kk.jar m.mf .
[
Read more about Packaging & Deployment of Java application.
http://java.sun.com/docs/books/tutorial/deployment/jar/index.html
]
DEPLOY & EXECUTE
Copy the kk.jar anywhere or any folder and issue following command to execute it.
> java -jar kk.jar