您的位置:首页 > 编程语言 > Java开发

java 解压缩代码

2015-10-14 10:59 411 查看
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 java.util.zip.ZipEntry;

import java.util.zip.ZipFile;

public class Decompression {

public static void main(String[] args) {

String tat = "F:\\WDJDownload\\question.zip";

String tatout = "F:\\WDJDownload\\out\\";

unzipZipFile(tat, tatout);

}

public static final void writeFile(InputStream in, OutputStream out)

throws IOException {

byte[] buffer = new byte[1024];

int len;

while ((len = in.read(buffer)) >= 0)

out.write(buffer, 0, len);

in.close();

out.close();

}

public static void unzipZipFile(String zipFileName, String directoryToExtractTo) {

@SuppressWarnings("rawtypes")

Enumeration entriesEnum;

ZipFile zipFile;

try {

zipFile = new ZipFile(zipFileName);

entriesEnum = zipFile.entries();

File directory = new File(directoryToExtractTo);

if (!directory.exists()) {

directory.mkdir();

System.err.println("...Directory Created -" + directoryToExtractTo);

}

while (entriesEnum.hasMoreElements()) {

try {

ZipEntry entry = (ZipEntry)entriesEnum.nextElement();

if (entry.isDirectory()) {

/**

* Currently not unzipping the directory structure.

* All the files will be unzipped in a Directory

*

**/

} else {

System.err.println("Extracting file: " + entry.getName());

/**

* The following logic will just extract the file name

* and discard the directory

*/

int index = 0;

String name = entry.getName();

index = entry.getName().lastIndexOf("/");

if (index > 0 && index != name.length())

name = entry.getName().substring(index + 1);

System.out.println(name);

writeFile(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(directoryToExtractTo + name)));

}

} catch (Exception e) {

e.printStackTrace();

}

}

zipFile.close();

} catch (IOException ioe) {

System.err.println("Some Exception Occurred:");

ioe.printStackTrace();

return;

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: