我正在替换或更新jar文件中某个目录内的某些文件。如何替换jar文件中某个目录内的某些文件?
我已阅读过几篇文章。在这个环节Updating .JAR's contents from code
正在非常有帮助,我听不懂的作用和使用ZipInputStream,ZipOutputStream和的ZipEntry的,等的代码(JarUpdater类)给出..
然而,当我运行它,
- 我有一个EOF异常
[由MK7编辑:我发现了jar文件已损坏我通过它去了20次左右之后。所以在我用新的jar文件替换之后,EOF Exception就消失了。下面的其他两个问题仍然没有解决]
这两个新的xml文件只被复制到jar文件的“根目录”。
这两个新的xml文件从不替换名为/ conf的目录内的两个原始文件。
为了用新的替换xml文件,我应该更改哪行代码?
通过System.out.println,我确实看到while循环遍历每个目录并按照预期在每个文件上进行比较。一个新的临时罐子也是按照预期创建的...... 我认为声明“notInFiles = false”会照顾我的需要,但它不是。
如何进入/ conf并仅替换这两个文件,而不在jar文件的根目录下留下副本?
我错过了什么?感谢您的任何见解!
下面是该链接的代码。
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class JarUpdater {
public static void main(String[] args) {
File[] contents = {new File("abc.xml"),
new File("def.xml")};
File jarFile = new File("xyz.jar");
try {
updateZipFile(jarFile, contents);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void updateZipFile(File jarFile,
File[] contents) throws IOException {
// get a temp file
File tempFile = File.createTempFile(jarFile.getName(), null);
// delete it, otherwise you cannot rename your existing zip to it.
tempFile.delete();
System.out.println("tempFile is " + tempFile);
boolean renameOk=jarFile.renameTo(tempFile);
if (!renameOk)
{
throw new RuntimeException("could not rename the file "+jarFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
}
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(jarFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
String name = entry.getName();
boolean notInFiles = true;
for (File f : contents) {
System.out.println("f is " + f);
if (f.getName().equals(name)) {
// that file is already inside the jar file
notInFiles = false;
System.out.println("file already inside the jar file");
break;
}
}
if (notInFiles) {
System.out.println("name is " + name);
System.out.println("entry is " + entry);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(name));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
entry = zin.getNextEntry();
}
// Close the streams
zin.close();
// Compress the contents
for (int i = 0; i < contents.length; i++) {
InputStream in = new FileInputStream(contents[i]);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(contents[i].getName()));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
// Complete the ZIP file
out.close();
tempFile.delete();
}
}
我只是仔细检查。代码是否有out.closeEntry();和in.close(); – mk7 2014-10-02 07:35:11
这是jar文件被损坏。所以在我替换了jar文件之后,EOF异常消失了。我编辑了我的原始问题,并删除了我第一次遇到的EOF异常问题。但即使是现在,我仍然没有取代这两个文件。 – mk7 2014-10-02 07:37:04
添加代码以正确检查条目是否要被替换(您没有正确检查,因此您没有过滤掉您想要替换的条目)。 – icza 2014-10-02 07:39:45