[英]Java - Removal of META-INF from jar not working
我目前正在開發一個將mods安裝到Minecraft的應用程序,並且版本3.1DEV即將完成,唯一阻止我的是我的代碼不會刪除META-INF,這是我的代碼
ZipInputStream modZip = new ZipInputStream(new FileInputStream(mod.getDir()));
ZipInputStream minecraftZip = new ZipInputStream(new FileInputStream(new File(mcDir + "\\bin\\", "minecraft.jar")));
ZipOutputStream tmpZip = new ZipOutputStream(new FileOutputStream(new File("temp\\tmp.jar")));
byte[] buffer = new byte[1024];
for(ZipEntry ze = modZip.getNextEntry(); ze != null; ze = modZip.getNextEntry())
{
tmpZip.putNextEntry(ze);
for(int read = modZip.read(buffer); read != -1; read = modZip.read(buffer))
{
tmpZip.write(buffer, 0, read);
}
tmpZip.closeEntry();
}
modZip.close();
for(ZipEntry ze = minecraftZip.getNextEntry(); ze != null; ze = minecraftZip.getNextEntry())
{
try
{
boolean isMetaInf = false;
if(ze.getName().contains("META-INF"))
{
isMetaInf = true;
}
if(!isMetaInf)
{
tmpZip.putNextEntry(ze);
for(int read = minecraftZip.read(buffer); read != -1; read = minecraftZip.read(buffer))
{
tmpZip.write(buffer, 0, read);
}
tmpZip.closeEntry();
}
}
catch(Exception e)
{
continue;
}
}
minecraftZip.close();
tmpZip.flush();
tmpZip.close();
File tmp = new File("temp//tmp.jar");
tmp.renameTo(new File("temp//minecraft.jar"));
File minecraft = new File(mcDir + "\\bin\\minecraft.jar");
minecraft.delete();
FileUtils.copyFile(new File("temp\\minecraft.jar"), minecraft);
tmp.delete();
歡迎任何鏈接或示例
問題出在邏輯上,讓我們來看一下:
!isMetaInf
部分 zip條目已添加到臨時zip:
tmpZip.putNextEntry(ze);
您將整個Minecraft zip從頭到尾寫到temp zip中:
for(int read = minecraftZip.read(buffer); read != -1; read = minecraftZip.read(buffer)) { tmpZip.write(buffer, 0, read); } tmpZip.closeEntry();
此時,您無需中斷循環,因此將對jar中的每個文件重復此過程。
如果您只刪除手動的讀寫循環,則可以在最后調用close()
時允許ZipOutputStream為您完成所有編寫工作;或者,如果您使用Java 7,則可以使用try- with-resources:
public static void copyWithoutMetaInf(final String originalZip, final String newZip) throws IOException
{
try (final ZipInputStream zip = new ZipInputStream(new FileInputStream(originalZip));
final ZipOutputStream zop = new ZipOutputStream(new FileOutputStream(newZip)))
{
ZipEntry entry;
while((entry = zip.getNextEntry()) != null)
{
if(!entry.getName().contains("META-INF"))
{
zop.putNextEntry(entry);
}
}
}
}
public static void main(String[] args) throws IOException
{
copyWithoutMetaInf("1.6.4.jar", "copy.jar");
}
對於較舊的版本,是否為:
public static void copyWithoutMetaInf(final String originalZip, final String newZip) throws IOException
{
final ZipInputStream zip = new ZipInputStream(new FileInputStream(originalZip));
final ZipOutputStream zop = new ZipOutputStream(new FileOutputStream(newZip));
ZipEntry entry;
while((entry = zip.getNextEntry()) != null)
{
if(!entry.getName().contains("META-INF"))
{
zop.putNextEntry(entry);
}
}
zip.close();
zop.close();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.