打包你需要的基本类、其他的不要

看了一篇瘦身文件、记录一下、http://nonconductor.bokee.com/5085956.html

源代码如下

/*
* Alipay.com Inc.
* Copyright (c) 2004-2008 All Rights Reserved.
*/
package com.beyond.web.trade;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;

public class Packager {
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        File f = new File("C:/Documents and Settings/en.xuze/hello.list");
        Packager pkger = new Packager();
        pkger.debugEnabled = true;
        List ret = pkger.parseOutput(new FileInputStream(f));
        pkger.pkgResources(ret, "C:/Documents and Settings/en.xuze/Hello.jar");
    }

    private boolean debugEnabled;

    public List parseOutput(InputStream in) throws IOException {
        ArrayList ret = new ArrayList();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = reader.readLine();
        while (line != null) {
            if (line.matches("\\[Loaded .* from .*")) {
                if (debugEnabled)
                    System.out.println("Matches:" + line);
                ret.add(line.substring(8, line.indexOf(" from ")));
            } else {
                if (debugEnabled)
                    System.out.println("UnMatches:" + line);
            }
            line = reader.readLine();
        }
        return ret;
    }

    public void pkgResources(List res, String fileName) throws IOException {
        File f = new File(fileName);
        if (!f.exists()) {
            f.createNewFile();
        }
        byte[] buf = new byte[1024];
        JarOutputStream out = new JarOutputStream(new FileOutputStream(fileName));

        for (Iterator iterator = res.iterator(); iterator.hasNext();) {
            InputStream in = null;
            try {
                String s = (String) iterator.next();
                s = s.replace('.', '/') + ".class";
                if (debugEnabled) {
                    System.out.println("adding: " + s);
                }
                in = this.getClass().getClassLoader().getResourceAsStream(s);
                out.putNextEntry(new ZipEntry(s));
                int w = in.read(buf);
                while (w >= 0) {
                    out.write(buf, 0, w);
                    w = in.read(buf);
                }
            } catch (Exception e) {
                e.printStackTrace();
                // TODO: handle exception
            } finally {
                in.close();
            }
        }
        out.finish();
        out.close();
    }
}


你可能感兴趣的:(java,C++,c,F#,C#)