java 文件压缩_Java生成压缩文件(zip、rar 格式)

/*** 递归压缩文件

*@paramoutput ZipOutputStream 对象流

*@paramfile 压缩的目标文件流

*@paramchildPath 条目目录*/

private static voidzip(ZipOutputStream output,File file,String childPath){

FileInputStream input= null;try{//文件为目录

if(file.isDirectory()) {//得到当前目录里面的文件列表

File list[] =file.listFiles();

childPath= childPath + (childPath.length() == 0 ? "" : "/")+file.getName();//循环递归压缩每个文件

for(File f : list) {

zip(output, f, childPath);

}

}else{//压缩文件

childPath = (childPath.length() == 0 ? "" : childPath + "/")+file.getName();

output.putNextEntry(newZipEntry(childPath));

input= newFileInputStream(file);int readLen = 0;byte[] buffer = new byte[1024 * 8];while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {

output.write(buffer,0, readLen);

}

}

}catch(Exception ex) {

ex.printStackTrace();

}finally{//关闭流

if (input != null) {try{

input.close();

}catch(IOException ex) {

ex.printStackTrace();

}

}

}

}/*** 压缩文件(文件夹)

*@parampath 目标文件流

*@paramformat zip 格式 | rar 格式

*@throwsException*/

public static String zipFile(File path,String format) throwsException {

String generatePath= "";if( path.isDirectory() ){

generatePath= path.getParent().endsWith("/") == false ? path.getParent() + File.separator + path.getName() + "." + format: path.getParent() + path.getName() + "." +format;

}else{

generatePath= path.getParent().endsWith("/") == false ? path.getParent() +File.separator : path.getParent();

generatePath+= path.getName().substring(0,path.getName().lastIndexOf(".")) + "." +format;

}//输出流

FileOutputStream outputStream = newFileOutputStream( generatePath );//压缩输出流

ZipOutputStream out = new ZipOutputStream(newBufferedOutputStream(outputStream));

zip(out, path,"");

out.flush();

out.close();returngeneratePath;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值