将jar文件输出字节流

使用fat jar  将一个工程打包后,使用以下代码 将jar输出为字节流

    public final static byte[] findJarBytes(String path){
        File file = new File(path);
        try{
            FileInputStream fis = new FileInputStream(file);
            JarInputStream jis = new JarInputStream(fis);
            Manifest manifest = jis.getManifest();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            JarOutputStream jos = null;
            if(manifest!=null)
                jos = new JarOutputStream(out,jis.getManifest());
            else jos = new JarOutputStream(out);
            
            JarEntry e = null;while ((e=jis.getNextJarEntry()) != null){
                System.out.println(e.getName());
                jos.putNextEntry(e);
            }
            jos.finish();
            jos.close();
            out.close();
            jis.close();
            fis.close();
            return out.toByteArray();
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }

经测试成功输出

使用ant 打包成jar包,使用同样的代码却发现抛出

java.util.zip.ZipException: invalid entry size (expected 5103 but got 0 bytes)
    at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:243)
    at java.util.zip.ZipOutputStream.putNextEntry(ZipOutputStream.java:177)
    at java.util.jar.JarOutputStream.putNextEntry(JarOutputStream.java:109)
    at com.meteorite.holy.verify.util.JarUtil.findJarBytes(JarUtil.java:136)

比较两个jar包后,发现只有MANIFEST.MF文件不一致,替换成之前成功的,发现同样报错,至今不解,大致估计是fat jar 和 ant jar 生成方式不同

折腾了一会,将代码中间的替换成

            byte[] bytes = new byte[1024];
            while ((e=jis.getNextJarEntry()) != null){
                System.out.println(e.getName());
                jos.putNextEntry(e);
                int len = 0;
                while((len = jis.read(bytes, 0, bytes.length))!=-1){
                    jos.write(bytes, 0, len);
                }
            }        

经测试成功!

posted on 2014-08-20 10:41  NeverLose  阅读(591)  评论(0编辑  收藏  举报

导航