Method to read data from a Java jar file

  • 2020-04-01 03:55:24
  • OfStack

This article illustrates how to read data from a Java jar file. Share with you for your reference. The details are as follows:

Java Archive (JAR) files are packaged based on Java technology. They allow developers to package all related content (.class, pictures, sounds, support files, etc.) into a single file. The JAR file format supports compression, authentication, and versioning, among many other features.

Getting the contents of the file it contains from a JAR file is tricky, but not impossible. This tip will show you how to get a file from a JAR file. We will first get the file directory in the JAR file and then read the specified file.

If you are familiar with the common ZIP format, you will find that the JAR file is not much different from it. JAR files provide a way to package multiple files into one file, and each file that is packaged can be compressed separately. A JAR file can be added, called a manifestπ , which allow developers to add additional information about the content. For example, the manifest can indicate which file in the JAR file started the application, or specify the version of the library, and so on.

The standard Java 2 SDK provides a jar tool that lets you read and write jar files from the console. Then, there may be times when you want to read and write JAR files in your program. (this tip only covers reading JAR files in your program.) I'm glad you can do that, and you don't have to worry about unpacking, because the library already handles it for you. The classes you will use are in the java.util.jar. The main class to use here is the JarFile class, which is a reference to the.jar file itself. Each of these files is referenced by JarEntry.

Now, pass an argument to the JarFile constructor to create an instance of JarFile. The argument may be a String or a File, which is the location of an.jar File:

JarFile jarFile = new JarFile("thefile.jar");

or

File file = new File("thefile.jar");
JarFile jarFile = new JarFile(file);

It also has some other constructors that support authentication and mark files for deletion. But we're not going to get into constructors here.

After you get a reference to a JAR file, you can read the directory of its contents. The entries method of JarFile returns an Enumeration object for all entries. You can also get its properties, authentication information, and other information, such as the name and size of the entry, from the manifest file.


//Note: enum is a keyword in Java 5.0, so this example should fail to compile in 5.0
//But the English original was published before Java 5.0, so you can use enum as the variable name
//No changes have been made here in keeping with the original
Enumeration enum = jarFile.entries();
while (enum.hasMoreElements()) {
  process(enum.nextElement());
}

As mentioned before, each individual is a JarEntry. This class has several methods such as getName, getSize, and getCompressedSize.

Let's illustrate how to use these features in a program. The following program displays a list of the contents of the JAR file and the names, sizes, and compressed sizes of the items. (this is very similar to using a jar command with arguments "t" and "v".)


import java.io.*;
import java.util.*;
import java.util.jar.*;
public class JarDir {
  public static void main (String args[]) 
    throws IOException {
    if (args.length != 1) {
      System.out.println("Please provide a JAR filename");
      System.exit(-1);
    }
    JarFile jarFile = new JarFile(args[0]);
    Enumeration enum = jarFile.entries();
    while (enum.hasMoreElements()) {
      process(enum.nextElement());
    }
  }
  private static void process(Object obj) {
    JarEntry entry = (JarEntry)obj;
    String name = entry.getName();
    long size = entry.getSize();
    long compressedSize = entry.getCompressedSize();
    System.out.println(name + " " + size + " " + compressedSize);
  }
}

If you use jce.jar in J2SE 1.4.1 to experiment with the JarDir program above, you should look at output like the following (in... More files should be displayed) :


META-INF/MANIFEST.MF  5315  1910
META-INF/4JCEJARS.SF  5368  1958
META-INF/4JCEJARS.DSA  2207  1503
META-INF/    0    2
javax/ 0    0
javax/crypto/  0    0
javax/crypto/interfaces/    0    0
javax/crypto/interfaces/DHKey.class   209   185
javax/crypto/interfaces/DHPublicKey.class    265   215
javax/crypto/interfaces/DHPrivateKey.class   267   215
javax/crypto/interfaces/PBEKey.class  268   224
javax/crypto/SecretKey.class  167   155
...

Notice the lines at the top of the input that contain meta-inf, which are menifest and security verification information. The item with a size of 0 is not a file, but a directory.

To actually read the contents of the file from the JAR file, you must get the InputStream of the corresponding entry. This is different from JarEntry. JarEntry contains only the entry information, but not the actual content. It's a lot like the difference between a File and a FileInputSteram. Only access the File, never open the corresponding File, it only read the information in the directory. Here's how to get an InputStream from an entry:

InputStream input = jarFile.getInputStream(entry);

Once you have the input stream, you just need to read it like any other stream. If it is a text stream, remember to use a Reader to fetch characters from the stream. For a byte stream, such as a picture, you have to read directly.

The following program demonstrates reading from a JAR file. When you run the program, you need to specify the file name to read from the JAR file, which must be a text file type.


import java.io.*;
import java.util.jar.*;
public class JarRead {
  public static void main (String args[]) 
    throws IOException {
    if (args.length != 2) {
      System.out.println("Please provide a JAR filename and file to read");
      System.exit(-1);
    }
    JarFile jarFile = new JarFile(args[0]);
    JarEntry entry = jarFile.getJarEntry(args[1]);
    InputStream input = jarFile.getInputStream(entry);
    process(input);
    jarFile.close();
  }
  private static void process(InputStream input) 
    throws IOException {
    InputStreamReader isr = 
      new InputStreamReader(input);
    BufferedReader reader = new BufferedReader(isr);
    String line;
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    reader.close();
  }
}

Suppose you have a jar file called myfiles.jar, and you have a text file called spider.txt. Pider. TXT contains the following text:


The itsy bitsy spider 
Ran up the water spout
Down came the rain and
Washed the spider out 

Run the following command to display the contents of the text file in the JAR file:

java JarRead myfiles.jar spider.txt

I hope this article has been helpful to your Java programming.


Related articles: