请教:如何用java代码把一个jar包里的文件替换掉

xiao_long_guo 2011-06-23 11:38:10
如题:

假设存在一个jar包,里面的有些文件需要替换。之前都是手工用winara打开不解压,然后把需要改变的文件黏贴进去替换的。如果存在很多图片的话,我希望通过代码实现。

请教如何实现!



...全文
696 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
飞跃颠峰 2011-06-24
  • 打赏
  • 举报
回复
JDK提供了一个JarFile类用来处理Jar文件的,不过只提供了读的功能

你可以通过如下步骤实现你的目标:
1) 通过JarFile读出Jar包信息。
2) 根据读出的信息将Jar包解压至临时目录。
3) 在临时目录里替换文件。
4) 通过RunTime.exex()执行控制台命令重新生成Jar包

附一段别人写的解压Jar包代码:


public static void unzip(ZipFile zipFile, String localPath, int bufferSize) {
byte[] buffer = new byte[bufferSize];
ZipInputStream zip = null;
ZipEntry zipEntry = null;
try {
zip = new ZipInputStream(new FileInputStream(zipFile.getName()));
while ((zipEntry = zip.getNextEntry()) != null) {
File file = new File(localPath, zipEntry.getName()).getAbsoluteFile();
System.out.println(file.getName());
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
file.createNewFile();
long size = zipEntry.getSize();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
int readLen = -1;
while (size != 0) {
readLen = zip.read(buffer);
size -= readLen;
if (readLen != -1) {
fos.write(buffer, 0, readLen);
}
}
} finally {
if (fos != null) {
fos.close();
}
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (zip != null) {
zip.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
淫生杯具 2011-06-24
  • 打赏
  • 举报
回复
一楼说的很明白,思路清晰。
小绵羊 2011-06-24
  • 打赏
  • 举报
回复
java提供了zip操作,jar文件实际是使用zip压缩的,看一楼的代码就知道
Fly_m 2011-06-24
  • 打赏
  • 举报
回复
使用ant里面的jarEntity工具,去读写jar工具。
安心逍遥 2011-06-24
  • 打赏
  • 举报
回复
顶楼上的
qybao 2011-06-24
  • 打赏
  • 举报
回复
写个bat文件,bat调用jar命令解压,然后调用copy命令把图片拷贝到相应的文件夹,然后再调用jar归档
在java里用Runtime.getRuntime().exec调用bat

81,095

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧