急!!!想实现通过java方式压缩文件并提供下载功能,在线等!!! 20
网上找到一些代码,但是实践上有问题,现在能够批量生成所需要的文件,文件所在的文件夹路径也能获取,但是实现不了压缩文件夹。求大神帮助!!!...
网上找到一些代码,但是实践上有问题,现在能够批量生成所需要的文件,文件所在的文件夹路径也能获取,但是实现不了压缩文件夹。求大神帮助!!!
展开
1个回答
展开全部
给你一个代码吧。
/**
* 文件夹压缩。输入路径不能与输出路径相同
* zip("c:\\webserver\\test.zip","c:\\test1");
* @param zipFileName
* @param inputFile
* @throws Exception
*/
public static void zipFold(String zipFileName,String inputFilePath)throws Exception{
zip(zipFileName,new File(inputFilePath));
}
private static void zip(String zipFileName,File inputFile)throws Exception{
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
zipFold(out,inputFile,"");
out.close();
}
private static void zipFold(ZipOutputStream out,File f,String base)throws Exception{
if (f.isDirectory())
{
File[] fl=f.listFiles();
base=base.length()==0?"":base+"/";
for (int i=0;i<fl.length ;i++ )
{
zipFold(out,fl[i],base+fl[i].getName());
}
}
else
{
out.putNextEntry(new ZipEntry(base));
FileInputStream in=new FileInputStream(f);
int b;
while ((b=in.read()) != -1)
out.write(b);
in.close();
}
}
/**
* 文件夹压缩。输入路径不能与输出路径相同
* zip("c:\\webserver\\test.zip","c:\\test1");
* @param zipFileName
* @param inputFile
* @throws Exception
*/
public static void zipFold(String zipFileName,String inputFilePath)throws Exception{
zip(zipFileName,new File(inputFilePath));
}
private static void zip(String zipFileName,File inputFile)throws Exception{
ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName));
zipFold(out,inputFile,"");
out.close();
}
private static void zipFold(ZipOutputStream out,File f,String base)throws Exception{
if (f.isDirectory())
{
File[] fl=f.listFiles();
base=base.length()==0?"":base+"/";
for (int i=0;i<fl.length ;i++ )
{
zipFold(out,fl[i],base+fl[i].getName());
}
}
else
{
out.putNextEntry(new ZipEntry(base));
FileInputStream in=new FileInputStream(f);
int b;
while ((b=in.read()) != -1)
out.write(b);
in.close();
}
}
追问
谢谢了啊 最后这个功能我自己写出来
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询