1 & 2 是简单的手动操作,将条目从 Jar 复制到另一个添加或保留所需条目,删除原始文件并重命名新文件以替换它。
正如 jtahlbom 所指出的,Java Jar API 开箱即用地处理其余部分。
更新示例
这些都是非常基本的例子。他们向您展示了如何读写 Jar。基本上,您可以从中得出您需要做的所有其他事情。
我已经建立了一个个人图书馆(不包括在内),它基本上允许我传入一个InputStream
并将其写入一个OutputStream
,反之亦然。这意味着您可以从任何地方读取并写入任何地方,这可以满足您的大部分需求。
public void unjar(File jar, File outputPath) throws IOException {
JarFile jarFile = null;
try {
if (outputPath.exits() || outputPathFile.mkdirs()) {
jarFile = new JarFile(jar);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
File path = new File(outputPath + File.separator + entry.getName());
if (entry.isDirectory()) {
if (!path.exists() && !path.mkdirs()) {
throw new IOException("Failed to create output path " + path);
}
} else {
System.out.println("Extracting " + path);
InputStream is = null;
OutputStream os = null;
try {
is = jarFile.getInputStream(entry);
os = new FileOutputStream(path);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = is.read(byteBuffer)) != -1) {
os.write(byteBuffer, 0, bytesRead);
}
os.flush();
} finally {
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
}
}
}
} else {
throw IOException("Output path does not exist/could not be created");
}
} finally {
try {
jarFile.close();
} catch (Exception e) {
}
}
}
public void jar(File jar, File sourcePath) throws IOException {
JarOutputStream jos = null;
try {
jos = new JarOutputStream(new FileOutputStream(jar));
List<File> fileList = getFiles(sourcePath);
System.out.println("Jaring " + fileList.size() + " files");
List<String> lstPaths = new ArrayList<String>(25);
for (File file : fileList) {
String path = file.getParent().replace("\\", "/");
String name = file.getName();
path = path.substring(sourcePath.getPath().length());
if (path.startsWith("/")) {
path = path.substring(1);
}
if (path.length() > 0) {
path += "/";
if (!lstPaths.contains(path)) {
JarEntry entry = new JarEntry(path);
jos.putNextEntry(entry);
jos.closeEntry();
lstPaths.add(path);
}
}
System.out.println("Adding " + path + name);
JarEntry entry = new JarEntry(path + name);
jos.putNextEntry(entry);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
byte[] byteBuffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = fis.read(byteBuffer)) != -1) {
jos.write(byteBuffer, 0, bytesRead);
}
jos.flush();
} finally {
try {
fis.close();
} catch (Exception e) {
}
}
jos.closeEntry();
}
jos.flush();
} finally {
try {
jos.close();
} catch (Exception e) {
}
}
}
如果您花时间看,有许多示例说明如何从 SO 上的 zip/jar 文件中添加/删除条目