问题描述
我知道这是一项简单的任务,但在更改我的代码后它停止工作,我无法取回它!我使用两个函数来压缩和解压缩,即使它实际上做的是jar和unjar,但这不应该产生巨大的差异
I know that it is an easy task, but after changing my code it stopped working and I can't get it back! I use two functions to zip and unzip, even though what it actually does is "jar" and "unjar", but that shouldn't make a huge difference
public static void zipit(File[] infiles, JarOutputStream jos) throws Exception
{
zipit(infiles,"", jos);
}
public static void zipit(File[] infiles, String root, JarOutputStream jos) throws Exception
{
byte[] buffer = new byte[4096];
for(int i=0; i<infiles.length; i++)
{
// recursive call for subfolders... temporary
if(infiles[i].isDirectory())
{
zipit(infiles[i].listFiles(), infiles[i].getName() + "/", jos);
continue;
}
// create string with absolute path
String entryfile = root + infiles[i].getName();
JarEntry entry = new JarEntry(entryfile);
zos.putNextEntry(entry);
FileInputStream fis = new FileInputStream(infiles[i]);
int count;
while((count = fis.read(buffer, 0, buffer.length)) != -1)
zos.write(buffer, 0, count);
}
}
public static void unzipit(File zipfile, File outputfolder) throws Exception
{
JarFile jar = new JarFile(zipfile);
for(Enumeration entries = jar.entries(); entries.hasMoreElements(); )
{
JarEntry entry = (JarEntry) entries.nextElement();
File unzipped = new File(outputfolder, entry.getName());
if (entry.isDirectory() && !unzipped.exists())
{
unzipped.mkdirs();
continue;
}
else if (!unzipped.getParentFile().exists())
unzipped.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(unzipped);
InputStream in = jar.getInputStream(entry);
byte[] buffer = new byte[4096];
int count;
while((count = in.read(buffer, 0, buffer.length)) != -1)
fos.write(buffer, 0, count);
fos.close();
}
}
任何帮助/建议?
创建JarFile时出错:
The error occurs when creating the JarFile:
java.util.zip.ZipException: error in opening zip file
at java.util.zip.ZipFile.open(Native Method)
at java.util.zip.ZipFile.<init>(ZipFile.java:131)
at java.util.jar.JarFile.<init>(JarFile.java:150)
at java.util.jar.JarFile.<init>(JarFile.java:114)
推荐答案
我不知道这是不是你的问题,但一般来说完成写作后关闭每个zip条目的良好做法。
I don't know if this is your problem or not, but it is generally good practice to close each zip entry after you finish writing.
参见。
在您显示的代码中,zip中的最后一个条目不会被关闭。您也不会显示关闭JarOutputStream本身的位置。这可能会导致您创建无效的zip文件,这些文件在使用您的其他方法回读时会出错。
In the code that you show, the very last entry in the zip would not be closed. You also don't show where you close the JarOutputStream itself. This could be causing you to create invalid zip files, which would have errors when they are read back in using your other method.
这篇关于zip并在java中解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!