`

java zip压缩、解压缩

 
阅读更多
public class ZipTest {
/**
* zip压缩功能
* @throws Exception
*/
public static void testCreateZip() throws Exception{
long startTime = System.currentTimeMillis();
//压缩baseDir下所有文件,包括子目录
File file = new File("d:\\search_user_max.xml");

//压缩文件名
ZipOutputStream zos=new ZipOutputStream(new FileOutputStream("d:\\out.zip"));

ZipEntry ze=null;
byte[] buf=new byte[1024];
int readLen=0;

//创建一个ZipEntry,并设置Name和其它的一些属性
ze=new ZipEntry("search_user_max_create_zip.xml");
ze.setSize(file.length());
ze.setTime(file.lastModified());

//将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is=new BufferedInputStream(new FileInputStream(file));
while ((readLen=is.read(buf, 0, 1024))!=-1) {
zos.write(buf, 0, readLen);
}
is.close();

System.out.println("耗时:" + (System.currentTimeMillis() - startTime) + "ms");

zos.close();
}

/**
* 解压缩功能.
* @throws Exception
*/
public static void testReadZip() throws Exception{
long startTime = System.currentTimeMillis();
ZipFile zfile=new ZipFile("d:\\out.zip");
System.out.println(zfile.getName());
Enumeration zList=zfile.entries();
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("d:\\search_user_max_read_zip.xml"));
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("耗时:" + (System.currentTimeMillis() - startTime) + "ms");
}
zfile.close();
}

public static void main(String[] args) {
try {
// ZipTest.testCreateZip(); //压缩
ZipTest.testReadZip(); //解压
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics