在Java中操作Zip文件,压缩/解压

王朝java/jsp·作者佚名  2008-05-31
窄屏简体版  字體: |||超大  

可随意转载,但请注明出处及作者

SonyMusic

2003.05.28

==========================================================================

在Java中操作Zip文件,压缩/解压

package test.nothing;

import java.io.*;

import java.util.*;

import java.util.zip.*;

import com.beaconsystem.util.*;

import junit.framework.TestCase;

/**

* @author SonyMusic

*

* 用于测试java.util.zip包压缩和解压缩文件zip文件的例子.

* 基于JUnit编写,包括两个test方法,和三个辅助方法.

* 注重到使用过程中操作的全是流,所以不仅仅可以读写文件。这只是一个简单的例子.

*/

public class TestZipOp extends TestCase {

/**

* ConstrUCtor for TestZipOp.

* @param arg0

*/

public TestZipOp(String arg0) {

super(arg0);

}

public static void main(String[] args) {

junit.textui.TestRunner.run(TestZipOp.class);

}

/**

* zip压缩功能测试.

* 将d:\\temp\\zipout目录下的所有文件连同子目录压缩到d:\\temp\\out.zip.

* @throws Exception

*/

public void testCreateZip() throws Exception{

//压缩baseDir下所有文件,包括子目录

String baseDir="d:\\temp\\zipout";

List fileList=getSubFiles(new File(baseDir));

//压缩文件名

ZipOutputStream zos=new ZipOutputStream(new FileOutputStream("d:\\temp\\out.zip"));

ZipEntry ze=null;

byte[] buf=new byte[1024];

int readLen=0;

for (int i = 0; i <fileList.size(); i++) {

File f=(File)fileList.get(i);

System.out.print("Adding: "+f.getPath()+f.getName());

//创建一个ZipEntry,并设置Name和其它的一些属性

ze=new ZipEntry(getAbsFileName(baseDir, f));

ze.setSize(f.length());

ze.setTime(f.lastModified());

//将ZipEntry加到zos中,再写入实际的文件内容

zos.putNextEntry(ze);

InputStream is=new BufferedInputStream(new FileInputStream(f));

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

zos.write(buf, 0, readLen);

}

is.close();

System.out.println(" done...");

}

zos.close();

}

/**

* 测试解压缩功能.

* 将d:\\download\\test.zip文件解压到d:\\temp\\zipout目录下.

* @throws Exception

*/

public void testReadZip() throws Exception{

//InputStream is=new BufferedInputStream(new FileInputStream());

String baseDir="d:\\temp\\zipout";

ZipFile zfile=new ZipFile("d:\\download\\Test.zip");

System.out.println(zfile.getName());

Enumeration zList=zfile.entries();

ZipEntry ze=null;

byte[] buf=new byte[1024];

while(zList.hasMoreElements()){

//从ZipFile中得到一个ZipEntry

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航