After packaging a project with fat jar, use the following code to output the JAR file as a byte stream.
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; }
Output after test
Use ant to package it into a jar package.
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)
After comparing the two jar packages, we found that only the manifest. MF files are inconsistent. If they were successfully replaced, we found that the same error was reported, but we still don't understand it. It is generally estimated that the methods for generating fat jar and ant jar are different.
After a while, replace the Code
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); } }
Tested successfully!