Java Read JAR File: Complete Guide

In Java, you can use the java.util.jar.JarFile class to read the contents of files in a JAR file. Here is a simple example code:

import java.util.jar.JarFile;
import java.util.jar.JarEntry;
import java.io.InputStream;

public class ReadJarFile {

    public static void main(String[] args) {
        try {
            JarFile jarFile = new JarFile("path/to/your/jar/file.jar");
            JarEntry jarEntry = jarFile.getJarEntry("path/inside/jar/file.txt");
            
            if (jarEntry != null) {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                // 读取文件内容
                int data;
                while ((data = inputStream.read()) != -1) {
                    System.out.print((char) data);
                }
                
                inputStream.close();
            } else {
                System.out.println("File not found in JAR");
            }
            
            jarFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

In the example above, first a JarFile object is created and the path of the JAR file is specified. Then the getJarEntry method is used to retrieve a specific file entry from the JAR file, followed by using the getInputStream method to get the input stream of the file, finally the file content is read and outputted. It is important to remember to close the input stream and the JAR file after reading the file content.

bannerAds