批改Jar自述文件
修改Jar自述文件
public class ModifyManifest extends AbstractCmdTest{ // private String jarPath="E:\\xxx\\junit-4.8.1.jar"; //要修改自述文件的Jar包路径 // private String jarPath2="E:\\xxx\\junit.jar"; //jar包零时存放路径 @Override public boolean execute() { String jarPath=this.getInputInfo("jarPath").toString(); //获取需要修改自述文件的Jar包路径 String jarPath2=this.getInputInfo("jarPath2").toString();//获取Jar零时存放路径 Map manifestMap=(Map) this.getInputInfo("manifest"); //获取带有描述信息的Map try { JarFile jarFile = new JarFile(jarPath); //得到要修改的Jar包 Manifest mf=jarFile.getManifest(); //得到其自述文件 StringBuffer attributes=new StringBuffer(); //存放描述信息的StringBuffer Set maniSet=manifestMap.keySet(); for(Object obj:maniSet){ //向StringBuffer中添加Map中的信息 String key=obj.toString(); String value=(String)manifestMap.get(obj); attributes.append(key+value+"\n"); } //把Map中的信息以UTF-8的形式放到流 InputStream mfStream = new ByteArrayInputStream(attributes.toString().getBytes("UTF-8")); Manifest newmf=new Manifest(mfStream); //用包含Map信息的流生成Manifest SoftReference<Manifest> manifest=new SoftReference(newmf); //得到Manifest 软引用 Field filed=JarFile.class.getDeclaredField("manRef"); //得到SoftReference<Manifest>反射 filed.setAccessible(true); filed.set(jarFile, manifest); //*************输出信息确认修改正确********* Attributes a=jarFile.getManifest().getMainAttributes(); Set i=a.keySet(); for(Object o:i){ System.out.println(o.toString()+a.getValue(o.toString())); } //生成修改后的文件 JarOutputStream jarOutput=new JarOutputStream(new FileOutputStream(jarPath2),newmf);//用新的Manifest文件生成Jar输出流 JarInputStream jarInput = new JarInputStream(new FileInputStream(jarPath)); //jar文件输入流 JarEntry jarEntry=null; byte[] jarByte=new byte[4096]; while((jarEntry=jarInput.getNextJarEntry())!=null){ jarOutput.putNextEntry(jarEntry); int length; while((length=jarInput.read(jarByte))!=-1){ jarOutput.write(jarByte, 0, length); } jarOutput.closeEntry(); } jarOutput.flush(); jarOutput.close(); jarInput.close(); //用新生成的jar包覆盖原来的jar包 FileInputStream fileInput=new FileInputStream(jarPath2); FileOutputStream fileOutput=new FileOutputStream(jarPath); byte[] fileByte=new byte[4096]; int fileLength; while((fileLength=fileInput.read(fileByte))>0){ fileOutput.write(fileByte, 0,fileLength); } fileOutput.flush(); fileOutput.close(); fileInput.close(); File f=new File(jarPath2); f.delete(); return true; //返回true } catch (IOException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return false; } public static void main(String[] args){ //输入参数 Map manifest=new HashMap(); manifest.put("Manifest-Version:", " 123456789.0"); manifest.put("Ant-Version:", " Apache Ant 1.789.1"); manifest.put("Created-By:", " 1.5.0_20-141 (Apple Inc.)"); manifest.put("guga:", " gaaaaa"); M