如何替换指定jar中的class文件

karies karies 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
void backupJar(File fileFrom) throws IOException {

JarEntry jarEntry;
byte[] buffer = new byte[1024];
JarInputStream jarIn;
JarOutputStream jarOut;
JarFile jarfile;
Manifest manifest;

backFile = new File(fileFrom.getParentFile(), fileFrom.getName()
.replace(".jar", "_v1.jar"));
if (!backFile.exists())
backFile.createNewFile();
jarfile = new JarFile(fileFrom);
manifest = jarfile.getManifest();
jarIn = new JarInputStream(new FileInputStream(fileFrom));
jarOut = new JarOutputStream(new FileOutputStream(backFile), manifest);
while ((jarEntry = jarIn.getNextJarEntry()) != null) {

if ("META-INF/MANIFEST.MF".equals(jarEntry.getName()))
continue;
jarOut.putNextEntry(jarEntry);
int read;
while ((read = jarIn.read(buffer)) != -1) {
jarOut.write(buffer, 0, read);
}
jarOut.closeEntry();
}
jarOut.flush();
jarOut.close();
jarIn.close();
}

通过上面的代码,我可以成功复制一个jar文件

但现在的问题是,我需要将原来jar文件中的某几个class更新为现在工程下的source目录中的的class文件,需要如何操作,我是这样考虑的,但是总是异常无法得到正确结果,还望高手能够帮助解决问题!!!



void updataFile(File fileFrom) throws IOException {
JarEntry jarEntry;
byte[] buffer = new byte[1024];
JarInputStream jarIn;
JarOutputStream jarOut;
JarFile jarfile;
Manifest manifest;

File modifyFile = new File(fileFrom.getParentFile(), fileFrom.getName()
.replace(".jar", "_v2.jar"));
if (!modifyFile.exists())
modifyFile.createNewFile();
jarfile = new JarFile(fileFrom);
manifest = jarfile.getManifest();

jarIn = new JarInputStream(new FileInputStream(fileFrom));
jarOut = new JarOutputStream(new FileOutputStream(modifyFile), manifest);
while ((jarEntry = jarIn.getNextJarEntry()) != null) {
String jarName = jarEntry.getName();

if ("META-INF/MANIFEST.MF".equals(jarName))
continue;

jarOut.putNextEntry(jarEntry);

if (updateEntry.contains(jarName)) { //如果是需要更新的class的话
String name = "source\\"
+ jarName.substring(jarName.lastIndexOf("/") + 1);

DataInputStream temp = new DataInputStream(new FileInputStream(name));
int read;
while ((read = temp.read(buffer)) != -1) {
jarOut.write(buffer, 0, read);
System.out.println(buffer);
}

} else {
int read;
while ((read = jarIn.read(buffer)) != -1)
jarOut.write(buffer, 0, read);
System.out.println("---class--2--------> "
+ jarEntry.getName());
}

jarOut.closeEntry();
}
jarOut.flush();
jarOut.close();
jarIn.close();

}
...全文
评论 4
收藏 已收藏
分享
返回顶部
karies
Java SE 62,621 成员 307,251 内容