创建新的 zip 文件时,此异常意味着什么?
java.util.zip.ZipException:太短而不能 Zip
java.util.zipException: too short to be zip 意味着您的 Zip 无效。请检查您正在创建有效的 zip。
您可以找到示例
我已经验证并且下面的代码正在运行。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
public class CreateZipFileDirectory {
public static void main(String args[])
{
try
{
String zipFile = "Path where zip needs to be creaetd e.g.zipdemo.zip";
String sourceDirectory = "directory which contains files.";
//create byte buffer
byte[] buffer = new byte[1024];
/*
* To create a zip file, use
*
* ZipOutputStream(OutputStream out)
* constructor of ZipOutputStream class.
*
*/
//create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipFile);
//create object of ZipOutputStream from FileOutputStream
ZipOutputStream zout = new ZipOutputStream(fout);
//create File object from directory name
File dir = new File(sourceDirectory);
//check to see if this directory exists
if(!dir.isDirectory())
{
System.out.println(sourceDirectory + " is not a directory");
}
else
{
File[] files = dir.listFiles();
for(int i=0; i < files.length ; i++)
{
System.out.println("Adding " + files[i].getName());
//create object of FileInputStream for source file
FileInputStream fin = new FileInputStream(files[i]);
/*
* To begin writing ZipEntry in the zip file, use
*
* void putNextEntry(ZipEntry entry)
* method of ZipOutputStream class.
*
* This method begins writing a new Zip entry to
* the zip file and positions the stream to the start
* of the entry data.
*/
zout.putNextEntry(new ZipEntry(files[i].getName()));
/*
* After creating entry in the zip file, actually
* write the file.
*/
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
/*
* After writing the file to ZipOutputStream, use
*
* void closeEntry() method of ZipOutputStream class to
* close the current entry and position the stream to
* write the next entry.
*/
zout.closeEntry();
//close the InputStream
fin.close();
}
}
//close the ZipOutputStream
zout.close();
System.out.println("Zip file has been created!");
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}
/*
Output of this program would be
Adding nonav.log
Adding ospreg.exe
Adding servers.ini
Adding setupisam.log
Adding sourceFile1.doc
Adding sourceFile2.doc
Zip file has been created!
*/
看一下readCentralDir()方法,您将不得不更深入地查看代码,但一般来说,一旦文件太短而不能成为 ZIP 文件,似乎就会引发此异常。
以下代码行(mRaf 是随机访问文件):
long scanOffset = mRaf.length() - ENDHDR;
if (scanOffset < 0) {
throw new ZipException("too short to be Zip");
}