java.util.jar


1. Create and Use a JAR file

// Create a JAR file
JarOutputStream jar = new JarOutputStream(new FileOutputStream("myjar.jar"));
jar.putNextEntry(new JarEntry("myfile.txt"));
jar.write("Hello world".getBytes());
jar.closeEntry();
jar.close();

// Use the JAR file
JarFile jarFile = new JarFile("myjar.jar");
JarEntry jarEntry = jarFile.getJarEntry("myfile.txt");
InputStream inputStream = jarFile.getInputStream(jarEntry);
byte[] data = inputStream.readAllBytes();
System.out.println(new String(data));

2. Create a JAR file from a Directory

import java.io.File;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

public class CreateJarFromDirectory {

    public static void main(String[] args) throws IOException {
        // Create a JAR file
        JarOutputStream jar = new JarOutputStream(new FileOutputStream("myjar.jar"));

        // Create a directory object
        File directory = new File("mydirectory");

        // Iterate over all files in the directory
        for (File file : directory.listFiles()) {
            // Create a JAR entry
            JarEntry jarEntry = new JarEntry(file.getName());

            // Put the JAR entry into the JAR file
            jar.putNextEntry(jarEntry);

            // Write the file data to the JAR entry
            jar.write(Files.readAllBytes(file.toPath()));

            // Close the JAR entry
            jar.closeEntry();
        }

        // Close the JAR file
        jar.close();
    }
}

3. Read Files from a JAR File

4. Extract Files from a JAR File

5. Create a JAR file with a Manifest

6. Create a JAR file with a Signature