我正在使用非常标准的代码使用ZipOutputStream
创建一个zip文件。由于某种原因,当我以ZipInputStream
的形式读回它时,ZipEntry
具有size=-1
。文件名已正确存储在ZipEntry
中。
(当我使用操作系统工具制作一个zip文件,然后将其读回时,大小是正确的,因此我认为问题出在ZipOutputStream
而不是ZipInputStream
)。
上下文是一个Spring MVC控制器。
我究竟做错了什么?
谢谢。
这是代码:
// export zip file
String file = "/Users/me/Desktop/test.jpg";
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file+".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
zos.putNextEntry(new ZipEntry("test.jpg"));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) > 0) {
zos.write(buffer, 0, bytesRead);
}
zos.closeEntry();
zos.close();
fis.close();
// import same file
String file2 = "/Users/me/Desktop/test.jpg.zip";
FileInputStream fis2 = new FileInputStream(file2);
ZipInputStream zis = new ZipInputStream(fis2);
ZipEntry entry = zis.getNextEntry();
// here: entry.getSize() = -1, zip.buf is an array of zeros...
// but if I unzip the file on my OS I see that the original file has been zipped...
最佳答案
您必须从流中获取下一个条目,例如以下示例:
http://www.roseindia.net/tutorial/java/corejava/zip/zipentry.html
当您手动设置尺寸时,它肯定会给您结果,就像您显示的是“ 64527”一样。
您最好看看zip示例。他们会给您清晰的图像。
另外:Create Java-Zip-Archive from existing OutputStream
尝试这样的事情:
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();