Use jar file in java

Java Jar file: How to read a file from a Jar file

Java jar file reading FAQ: Can you show me how a Java application can read a text file from own of its own Jar files?

Here’s an example of some Java code I’m using to read a file (a text file) from a Java Jar file. This is useful any time you pack files and other resources into Jar files to distribute your Java application.

How to read a Java Jar file, example #1

The source code to read a file from a Java Jar file uses the getClass and getResourceAsStream methods:

public void test3Columns() throws IOException < InputStream is = getClass().getResourceAsStream("3Columns.csv"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) < CSVLineTokenizer tok = new CSVLineTokenizer(line); assertEquals("Should be three columns in each row",3,tok.countTokens()); >br.close(); isr.close(); is.close(); >

The trick to reading text files from JAR files are these lines of code, especially the first line:

InputStream is = getClass().getResourceAsStream("3Columns.csv"); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr);

In my example I have a plain text file named » 3Columns.csv » in the same directory as the class that contains this method. Without a path stated before the filename (like » /foo/bar/3Columns.csv «) the getResourceAsStream method looks for this text file in its current directory.

Note that I’m doing all of this within the context of a JUnit test method. Also note that I’m throwing any exceptions that occur rather than handling them. I don’t recommend this for real world programming, but it works okay for my unit testing needs today.

I haven’t read through the Javadocs yet to know if all of those close statements at the end are necessary. I’ll try to get back to that later.

Java: How to read a Jar file, example #2

Here is a slightly more simple version of that method:

public String readFromJARFile(String filename) throws IOException < InputStream is = getClass().getResourceAsStream(filename); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) < sb.append(line); >br.close(); isr.close(); is.close(); return sb.toString(); >

In this sample I’ve eliminated the CSVLineTokenizer and replaced it with a simple StringBuffer , and I return a plain old String at the end of the method.

Also, if I didn’t stress it properly earlier, with this approach the resource file that you’re trying to read from must be in the same directory in the jar file as this class. This is inferred by the getClass().getResourceAsStream() method call, but I don’t think I really stressed that enough earlier.

Also, I haven’t looked at it in a while, but I think you can just call the is.close() method to close all your resources, you don’t have to make all the close calls I make here, but I’m not 100% positive.

Reading a file from a jar file as a File

Here’s one more example of how to do this, this time using some code from a current Scala project:

val file = new File(getClass.getResource("zipcode_data.csv").toURI)

Although the code shown is Scala, I think you can see that you can use this approach to read the file as a java.io.File instead of reading it as a stream.

Читайте также:  Http bt bashtel ru viewtopic php

One more Java «read from Jar file» example

While I’m working on another Java project, I just ran across another example of how to read a file from a Java jar file in this method:

private void playSound(String soundfileName) < try < ClassLoader CLDR = this.getClass().getClassLoader(); InputStream inputStream = CLDR.getResourceAsStream("com/devdaily/desktopcurtain/sounds/" + soundfileName); AudioStream audioStream = new AudioStream(inputStream); AudioPlayer.player.start(audioStream); >catch (Exception e) < // log this >>

As you can guess from looking at this code, this example shows how to read a resource file from a jar file in a java application, and in this approach, the resource file that I’m reading doesn’t have to be in the same directory as the Java class file. As you can imagine, this is a much more flexible approach.

Источник

Using JAR Files: The Basics

JAR files are packaged with the ZIP file format, so you can use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking. These tasks are among the most common uses of JAR files, and you can realize many JAR file benefits using only these basic features.

Even if you want to take advantage of advanced functionality provided by the JAR file format such as electronic signing, you’ll first need to become familiar with the fundamental operations.

To perform basic tasks with JAR files, you use the Java Archive Tool provided as part of the Java Development Kit (JDK). Because the Java Archive tool is invoked by using the jar command, this tutorial refers to it as ‘the Jar tool’.

As a synopsis and preview of some of the topics to be covered in this section, the following table summarizes common JAR file operations:

AppletClassName.class archive width=width height=height> 

This section shows you how to perform the most common JAR-file operations, with examples for each of the basic features:

Creating a JAR File

This section shows you how to use the Jar tool to package files and directories into a JAR file.

Viewing the Contents of a JAR File

You can display a JAR file’s table of contents to see what it contains without actually unpacking the JAR file.

Extracting the Contents of a JAR File

You can use the Jar tool to unpack a JAR file. When extracting files, the Jar tool makes copies of the desired files and writes them to the current directory, reproducing the directory structure that the files have in the archive.

Updating a JAR File

This section shows you how to update the contents of an existing JAR file by modifying its manifest or by adding files.

Running JAR-Packaged Software

This section shows you how to invoke and run applets and applications that are packaged in JAR files.

Additional References

The documentation for the JDK includes reference pages for the Jar tool:

Источник

Working with JAR and Manifest files In Java

Whenever a developer wants to distribute a version of his software, then all he want is to distribute a single file and not a directory structure filled with class files. JAR files were designed for this purpose. A JAR file can contain both class files and other file types like sound and image files which may be included in the project. All the files in a JAR file are compressed using a format similar to zip.

Читайте также:  Функции высокого порядка python

Creating a JAR file – more Options

A jar file is created using jar tool. The general command looks somewhat like this:

jar options jar-file [manifest-file] file1 file2 file3 .
  • jar – file : name of jar file on which you want to use jar tool.
  • file1, file2, file3 : files which you want to add inside a jar file. manifest-file is the name of file which contains manifest of that jar file, giving manifest-file as an argument is entirely optional.
  • c : Creates a new or empty archive and adds files to it. If any of the specified file name are directories, then the jar program processes them recursively.
  • C : Temporarily changes the directory.
  • e : Creates an entry point in the manifest.
  • f : Specifies the JAR file name as the second command-line argument. If this parameter is missing, jar will write the result to standard output (when creating a JAR file)or read it from standard input(when extracting or tabulating a JAR file).
  • i : Creates an index file.
  • m : Adds a manifest file to the JAR file. A manifest is a description of the archive contents and origin. Every archive has a default manifest, but you can supply your own if you want to authenticate the contents of the archive.
  • M : Does not create a manifest file for the entries.
  • t : Displays the table of contents.
  • u : Updates an existing JAR file.
  • v : Generates verbose output.
  • x : Extract files. If you supply one or more file names, only those files are extracted Otherwise, all files are extracted.
  • 0 : Stores without zip compression.

The options of jar command are almost similar to that of UNIX tar command. In windows you can also get help about various options of jar command just by typing jar in cmd and then pressing enter, the output will be somewhat similar to this:

jar command options

For creating a JAR file which have two classes server.class and client.class and a Jpeg image logo.jpeg, one need to write following command :

jar cvf chat.jar server.class client.class logo.jpeg

The output of above command will be somewhat like this:

It’s a better practice to use -v option along with jar command as you will get to know how the things are going on.

Manifest File

Each JAR file contains a manifest file that describe the features of the archive. Each JAR file have a manifest file by default. Default manifest file is named as MANIFEST.MF and is present in the META-INF subdirectory of archive. Although the default manifest file contains just two entries, but complex manifest files can have way more. Here, is what a default manifest file looks like –

Default manifest

The entries of manifest files are grouped into sections. Each section have two entries section name and its value. We will see a bit later how these sections can really help us in controlling the properties of our archive. Manifest file can also be updated by using the m option of jar command. But there are certain things which need to kept in mind while updating manifest file otherwise you may get the following creepy message.

java.io.IOException: invalid manifest format

Things to keep in mind while handling Manifest files:

  1. You should leave space between the name and value of any section in manifest file, like Version:1.1 is in valid section instead write Version: 1.1 that space between colon and 1.1 really matters a lot.
  2. While specifying the main class you should not add .class extension at the end of class name. Simply specify the main class by typing:

Now let’s come back and update the contents of our chat.jar archive. To update the manifest file we simply need to write the following command:

jar uvfm chat.jar manifest.txt

Here manifest.txt is the new manifest file, which has following contents:

The output of above command will be somewhat like this:

Here we are getting two warnings because we are trying to overwrite to previously present entries.

Executable Jar Files

You can use the e option of jar command to specify the entry point of your program, ie. class which you normally want to invoke when launching your Java application.

To create chat.jar file having client class as main class you need to write following command –

jar cvfe chat.jar client client.class server.class logo.jpeg

The output of above command will be somewhat like this:

Remember not to add .class extension after the name of class which you want to set main class.

Alternatively you can add a Main-Class entry in the manifest file and then update it. For the above example you just need to add this entry:

With main class being set one can simply run a jar program by writing following command –

Depending on operating system configuration, users may even be able to launch application by double clicking the JAR file icon.

Package Sealing

Finally, we are going to discuss about package sealing in Java. We can seal a package in Java to ensure that no further classes can add themselves to it. You may want to seal a package if you use a package visible classes, methods and fields in your code. Without package sealing, other classes can add themselves to the same package and thereby gain access to package visible features.

  • To achieve package sealing all one need to do is to put all classes of that package into a JAR file.
  • By default the packages in a jar file are not sealed but one can change the global default by adding few lines in manifest file.
  • Let’s again consider the case of our chat.jar archive, now the package of classes client.class and server.class is application and we want to seal this package all we need to do is to add following line in the manifest file and update it.
Name: application Sealed: true

This is all from my side on how to work with JAR files. Stay Tuned!!

This article is contributed by Abhey Rana(UselessCoder). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Источник

Оцените статью