修改JAR包中的文件(通用函数)

来源:互联网 发布:健身软件推荐 编辑:程序博客网 时间:2024/06/11 06:59
public static void editJar(String file,String EntryName,byte[] data) {//修改jar  try{   JarFile jf = new JarFile(file);   TreeMap tm = new TreeMap();   Enumeration es = jf.entries();   while(es.hasMoreElements())   {    JarEntry je = (JarEntry)es.nextElement();    byte[] b = getByte(jf.getInputStream(je));    tm.put(je.getName(),b);   }   JarOutputStream out = new JarOutputStream(new FileOutputStream(file));   Set set = tm.entrySet();   Iterator it = set.iterator();   boolean has = false;   while(it.hasNext())   {    Map.Entry me = (Map.Entry)it.next();    String name = (String)me.getKey();    JarEntry jeNew = new JarEntry(name);    out.putNextEntry(jeNew);    byte[] b;    if(name.equals(EntryName))    {     b = data;     has = true;    }    else     b = (byte[])me.getValue();    out.write(b,0,b.length);   }   if(!has)   {    JarEntry jeNew = new JarEntry(EntryName);    out.putNextEntry(jeNew);    out.write(data,0,data.length);   }   out.finish();   out.close();  }catch(Exception e){} }配置文件和类文件一起打包到一个Jar中,如何读取/修改这个配置文件?---------------------------------------------------------------读取:String currentJarPath = URLDecoder.decode(YourClassName.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); //获取当前Jar文件名,并对其解码,防止出现中文乱码JarFile currentJar = new JarFile(currentJarPath);JarEntry dbEntry = currentJar.getJarEntry("包名/配置文件");InputStream in = currentJar.getInputStream(dbEntry);//以上YourClassName是class全名,也就是包括包名修改:JarOutputStream out = new FileOutputStream(currentJarPath);out.putNextEntry(dbEntry);out.write(byte[] b, int off, int len);  //写配置文件。。。out.close(); 

原创粉丝点击