ZipInputStream和ZipEntry的问题

zuoyangguang zuoyangguang 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
帮我看看,谢谢大家。

我用java代码生成了一个test.zip文件,然后调用getFileDataFromStream方法,

在getFileDataFromStream方法的data = new byte[(int) zipEntry.getSize()]; zipEntry.getSize()的值为-1.

若不用java代码生成test.zip文件,则没有问题。



package test;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.seasar.framework.util.InputStreamUtil;
public class Test {

/**
* @param args
*/
public static void main(String[] args) {

File file=new File("testentry");
ZipOutputStream zipOutputStream = null;
try {
// file.createNewFile();

FileWriter fw=new FileWriter(file);//建立FileWriter对象,并实例化fw
//将字符串写入文件
fw.write("大家好!");
fw.write("本书是《JSP编程技巧》");
fw.write("请多多指教!");
fw.write("email:stride@sina.com");
fw.close();
InputStream input=new FileInputStream(file);
zipOutputStream = new ZipOutputStream(new FileOutputStream("test.zip"));
ZipEntry zipEntry = new ZipEntry("testentry");
zipEntry.setComment("12121");
zipEntry.setTime(new Date().getTime());
zipEntry.setSize(file.length());

zipOutputStream.putNextEntry(zipEntry);

byte[] buf = new byte[1024];
int temp=0;
while ((temp = input.read(buf, 0, 1024)) != -1) {
zipOutputStream.write(buf, 0, temp);
}
//
// while((temp=input.read())!=-1){
// zipOutputStream.write(temp);
// }
input.close();
zipOutputStream.close();
FileInputStream fileInputStream=new FileInputStream("test.zip");

getFileDataFromStream(fileInputStream,"testentry");
file.delete();
file=new File("test.zip");
file.delete();
} catch (IOException e) {

e.printStackTrace();
}
// FileInputStream fileInputStream;
// try {
// fileInputStream = new FileInputStream("test.zip");
//
// getFileDataFromStream(fileInputStream,"testentry");
// } catch (IOException e) {
// e.printStackTrace();
// }
}

public static byte[] getFileDataFromStream(InputStream in,
String name) throws IOException {

byte[] data = null;
ZipInputStream zipIn = null;
if (in == null) {
return null;
}
try {
BufferedInputStream bi = new BufferedInputStream(in);

zipIn = new ZipInputStream(bi);

ZipEntry zipEntry = null;
while ((zipEntry = zipIn.getNextEntry()) != null) {

if (name.equals(zipEntry.getName())) {
data = new byte[(int) zipEntry.getSize()];
zipIn.read(data, 0, (int) zipEntry.getSize());
}
}
} catch (IOException e) {
throw e;
} finally {
if (zipIn != null) {
InputStreamUtil.close(zipIn);
}
}
return data;
}

}
...全文

相关推荐

评论 5
收藏 已收藏
分享
返回顶部
zuoyangguang
Java SE 62,621 成员 307,251 内容