apache zip java_java使用apache的工具类对zip(rar等压缩文件)进行解压的实例

java使用apache的工具类对zip(rar等压缩文件)进行解压的实例,java压缩文件解压源码实例:

先到Ant官网下载一个Ant,然后在项目中导入Ant.jar,直接上代码:(在import时要注意引入ant.jar中的压缩工具类)

package hoking.in.action;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Enumeration;

import org.apache.tools.zip.ZipEntry;

import org.apache.tools.zip.ZipFile;

/**

* Description: 此类用于…

*

* @author wunaigang(2005-6-21)

* @version 1.0.0

*/

public class Test {

public static void main(String[] args) {

Test t = new Test();

try {

t.releaseZipToFile(“G:\\changeFile.jar”, “G:\\test”);

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 测试解压缩功能. 将G:\\changeFile.jar连同子目录解压到G:\\test目录下.

*

* @throws Exception

*/

public void releaseZipToFile(String sourceZip, String outFileName)

throws IOException {

ZipFile zfile = new ZipFile(sourceZip);

Enumeration> zList = zfile.getEntries();

ZipEntry ze = null;

byte[] buf = new byte[1024];

while (zList.hasMoreElements()) {

// 从ZipFile中得到一个ZipEntry

ze = (ZipEntry) zList.nextElement();

if (ze.isDirectory()) {

continue;

}

// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中

OutputStream os = new BufferedOutputStream(new FileOutputStream(

getRealFileName(outFileName, ze.getName())));

InputStream is = new BufferedInputStream(zfile.getInputStream(ze));

int readLen = 0;

while ((readLen = is.read(buf, 0, 1024)) != -1) {

os.write(buf, 0, readLen);

}

is.close();

os.close();

System.out.println(“Extracted: ” + ze.getName());

}

zfile.close();

}

/**

* 给定根目录,返回一个相对路径所对应的实际文件名.

*

* @param baseDir

* 指定根目录

* @param absFileName

* 相对路径名,来自于ZipEntry中的name

* @return java.io.File 实际的文件

*/

private File getRealFileName(String baseDir, String absFileName) {

String[] dirs = absFileName.split(“/”);

// System.out.println(dirs.length);

File ret = new File(baseDir);

// System.out.println(ret);

if (dirs.length > 1) {

for (int i = 0; i < dirs.length – 1; i++) {

ret = new File(ret, dirs[i]);

}

}

if (!ret.exists()) {

ret.mkdirs();

}

ret = new File(ret, dirs[dirs.length - 1]);

return ret;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值