java unzip_Java zip and unzip demo

该代码示例展示了如何使用Java的ZipOutputStream和ZipInputStream类进行文件夹的压缩和解压操作。主要方法包括zipFolder()用于压缩文件夹,unzip()用于解压ZIP文件,实现了对文件及子文件夹的递归处理。
摘要由CSDN通过智能技术生成

目录结构如下:

84a86b03b1d67b3334a492fffabbc51b.png

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;

import java.util.zip.ZipOutputStream;

public class zipDemo {

public static void main(String[] args) {

try {

//zipFolder("/home/hadoop/test";);

unzip("/home/hadoop/mytest/test.zip","/home/hadoop/mytest/");

} catch (IOException e) {

e.printStackTrace();

}

}

static void zipFolder(String _path) throws IOException

{

Path path = Paths.get(_path);

String target = "/home/hadoop/mytest/test.zip";

//String target = path.getParent() +"/" + path.getFileName() +".zip";

/*

System.out.println(path.getFileName());

System.out.println(path.getRoot());

System.out.println(path.getParent());System.out.println(target);

*/

ZipOutputStream zo = new ZipOutputStream(new FileOutputStream(target));

zipFile(zo,path,"");

zo.close();

}

static void zipFile(ZipOutputStream zo,Path _path,String parentpath) throws IOException

{

File _file = _path.toFile();

if(_file.isFile())

{

byte[] buff = new byte[1024];

FileInputStream fi = new FileInputStream(_file);

int len;

zo.putNextEntry(new ZipEntry(parentpath +"/" + _file.getName()));

while((len=fi.read(buff))>0)

zo.write(buff, 0, len);

zo.closeEntry();

fi.close();

}

if(_file.isDirectory())

{

if(_file.listFiles().length==0)

{

zo.putNextEntry(new ZipEntry(parentpath.equals("")?_file.getName():parentpath + "/" + _file.getName() + "/"));

}

for(File __file : _file.listFiles())

zipFile(zo,__file.toPath(),parentpath.equals("")?_file.getName():parentpath+ "/" + _file.getName());

}

}

static void unzip(String path,String target) throws IOException

{

File targetfolder = new File(target);

ZipInputStream zi = new ZipInputStream(new FileInputStream(path));

ZipEntry ze = null;

FileOutputStream fo = null;

byte[] buff = new byte[1024];

int len;

while((ze = zi.getNextEntry())!=null)

{

File _file = new File(targetfolder,ze.getName());

if(!_file.getParentFile().exists()) _file.getParentFile().mkdirs();

if(ze.isDirectory())

{

_file.mkdir();

}

else //file

{

fo = new FileOutputStream(_file);

while((len=zi.read(buff))>0) fo.write(buff, 0, len);

fo.close();

}

zi.closeEntry();

}

zi.close();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值