首页 > 其他 > 详细

将jar文件输出字节流

时间:2014-08-20 12:02:22      阅读:384      评论:0      收藏:0      [点我收藏+]

使用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);
                }
            }        

经测试成功!

将jar文件输出字节流,布布扣,bubuko.com

将jar文件输出字节流

原文:http://www.cnblogs.com/gameluo/p/3924018.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!