JAR文件最小体积发布

import java.io.*;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;

/**
 * Created by jimyao on 2016/1/23.
 * 使用-XX:+TraceClassLoading输出程序所需要的class,定制jar文件
 */
public class Test6 {
    static BufferedReader fileIn;
    static ArrayList<String> newClassList;
    static JarInputStream jarIn;
    static JarOutputStream jarOut;
    static byte[] bytes;
    static final String rtFileName = "C://Program Files//Java//jdk1.8.0_65//jre//lib//rt.jar";

    public Test6() throws IOException {
        newClassList = new ArrayList<>();
        bytes = new byte[1024];
        jarIn = new JarInputStream(new BufferedInputStream(new FileInputStream(rtFileName)));
        jarOut = new JarOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\1\\newrt.jar")));
    }

    private static void doJar(String sourceFile) throws FileNotFoundException, IOException {

        try {
            fileIn = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile)));

            String readLine = null;
            while ((readLine = fileIn.readLine()) != null) {
                String[] subLine = readLine.split(" ");
                String newClass = subLine[1];
                newClassList.add(newClass.replace(".", "/").trim());
            }
            JarEntry entry = null;
            while ((entry = jarIn.getNextJarEntry()) != null) {
                String fullName = entry.getName();
                String className = entry.getName().substring(0, fullName.lastIndexOf("."));
                if (newClassList.contains(className)) {
                    jarOut.putNextEntry(entry);

                    int len = jarIn.read(bytes);
                    while (len != -1) {
                        jarOut.write(bytes, 0, len);
                        len = jarIn.read(bytes);
                    }
                }
            }
        } finally {
            if (fileIn != null)
                fileIn.close();
            if (jarIn != null)
                jarIn.close();
            if (jarOut != null)
                jarOut.close();

        }
    }
 
  public static void main(String... args) throws IOException {
        Test6 test6 = new Test6();
        test6.doJar("C:\\1\\sourceFile.txt");
    }
}

你可能感兴趣的:(java,jar)