今天用java.util.zip做文件压缩.写完程序后发现压缩包里带进了原文件的所有路径目录
/**
* 生成zip文件
* 返回zip文件地址
* @param imgids String[]
* @return String
*/
public String createZip(String[] imgids){
String[] filenames=getPath(imgids);//根据图片id返回路径
Date date=new Date();
byte[] buf=new byte[1024];
String outFilename=zippath+String.valueOf(date.getTime())+".zip";
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
for(int i=0;i<filenames.length;i++){
FileInputStream in=new FileInputStream(filenames[i]);
ZipEntry zipEntity=new ZipEntry(filenames[i]); //添加文件到压缩实体里
out.putNextEntry(zipEntity);
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.closeEntry();
in.close();
}
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
return outFilename;
}
其实问题出现在 ZipEntry zipEntity=new ZipEntry(filenames[i]); 我println这个filename[i]后发现这里是带了全路径的一个文件名.
解决方法
public String createZip(String[] imgids){
String[] filenames=getPath(imgids);
Date date=new Date();
byte[] buf=new byte[1024];
String outFilename=zippath+String.valueOf(date.getTime())+".zip";
try {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
for(int i=0;i<filenames.length;i++){
FileInputStream in=new FileInputStream(filenames[i]);
File file=new File(filenames[i]);
String filename=file.getName();//取得图片文件名
ZipEntry zipEntity=new ZipEntry(filename);//这里改成文件名就可以了
out.putNextEntry(zipEntity);
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.closeEntry();
in.close();
}
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
return outFilename;
}
一些细节的地方平时没怎么注意.导致在这么简单的问题上耗费了时间.该打该打
本文地址:http://com.8s8s.com/it/it13244.htm