不需解压修改jar包文件内容
修改jar内容,一般做法是先解压再修改最好再压缩成jar。看了下api发现可以直接通过修改InputStream内容去修改jar。
代码:
/** * 修改jar包内容 * @param jarPath * @param path * @throws Exception */ public static void makeJar(String jarPath,String path) throws Exception { try { JarOutputStream jos = new JarOutputStream(new FileOutputStream(path)); File jarFile = new File(jarPath); JarFile jf = new JarFile(jarFile); Enumeration<JarEntry> je = jf.entries(); while (je.hasMoreElements()) { JarEntry jar = je.nextElement(); System.out.println(jar.getName()); ZipEntry z = new ZipEntry(jar.getName()); InputStream in = jf.getInputStream(jar); jos.putNextEntry(z); //修改config.properties文件中的host位hehe if("config.properties".equals(jar.getName())){ jos.write(IOUtils.toString(in,"UTF-8").replace("host", "hehe").getBytes("UTF-8")); }else{ jos.write(IOUtils.toByteArray(in)); } jos.closeEntry(); } jos.close(); jf.close(); } catch (Exception e) { throw e; } } public static void main(String[] args) { try { makeJar("/Users/yz/fat.jar","/Users/yz/1.jar"); } catch (Exception e) { e.printStackTrace(); } }
反编译修改后的jar发现原来的jar包当中的config.properties已经修改成功了。