[英]Programatically copy one jar file into another jar file
我想使用以下代碼將jar文件復制到文件夾中
public static void copyJarFile(JarFile jarFile, File destDir) throws IOException {
String fileName = jarFile.getName();
String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
File destFile = new File(destDir, fileNameLastPart);
JarOutputStream jos = new JarOutputStream(new FileOutputStream(destFile));
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
InputStream is = jarFile.getInputStream(entry);
//jos.putNextEntry(entry);
//create a new entry to avoid ZipException: invalid entry compressed size
jos.putNextEntry(new JarEntry(entry.getName()));
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
jos.write(buffer, 0, bytesRead);
}
is.close();
jos.flush();
jos.closeEntry();
}
jos.close();
}
該程序運行良好。 但是,如果目標位置不是目錄而是jar文件,則此程序將無法運行。 即我想將一個jar文件復制到另一個jar文件中。 如何以編程方式做到這一點?
Jar文件只是具有特定文件結構和擴展名.jar的精美zip文件。 所以,如果你能夠用這個東西都堆到一個文件夾,該文件夾中有你要找的確切結構,你可以拉上該目錄為一個zip文件,然后重命名zip文件whatever.jar
代替whatever.zip
。
當您說I want to copy one jar file into another jar file
,您的意思到底是什么?
假設您原始的原始jar名為a.jar
,並且您想創建b.jar
。 您是否要像原來一樣將a.jar
所有項目都放在b.jar
中? 還是你想b.jar
包含稱為入口a.jar
即是一個完整的副本a.jar
?
如果您只是希望b.jar
將a.jar
所有項目都包含a.jar
,那么您當前的代碼應該可以使用,盡管這樣做的效率更高。 如果這是您的意思,我建議您直接復制文件。
如果要在b.jar
添加整個a.jar
作為條目,而不是循環瀏覽a.jar
的條目,則只需從a.jar
創建一個FileInputStream
並從中讀取。
InputStream is = new FileInputStream("a.jar");
jos.putNextEntry(new JarEntry("a.jar"));
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
jos.write(buffer, 0, bytesRead);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.