需求:
这一步也非常简单,主要是demo下ZipEntry的用法,就是把一个以zip扩展名结尾的文件进行解压缩。
所以我就直接贴上代码了:
实现:
-
-
-
-
-
-
-
-
-
-
-
-
- public class FolderZipper implements IFolderZipper {
-
-
-
- private static Logger logger = LoggerFactory.getLogger(FolderZipper.class);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public void unzip(String zipFileName, String destPath) throws Exception {
-
-
-
-
-
- if (zipFileName == null || zipFileName.trim().equals(EMPTY_STRING)) {
-
- if (logger.isErrorEnabled()) {
-
- logger.error("zipFileName parameter can't be null");
-
- }
-
- throw new ParameterNullException(ZIP_UNZIP_ERROR);
-
- }
-
-
-
- if (destPath == null) {
-
-
-
- if (logger.isErrorEnabled()) {
-
- logger.error("destPath parameter can't be null");
-
- }
-
- throw new ParameterNullException("ZIP_UNZIP_ERROR");
-
- }
-
-
-
-
-
- if (!zipFileName.trim().endsWith(ZIP_EXTENSION)) {
-
-
-
- if (logger.isErrorEnabled()) {
-
- logger.error("the zip file MUST BE end with zip suffix");
-
- }
-
- throw new ParameterInvalidException(ZIP_UNZIP_ERROR);
-
- }
-
-
-
- try {
-
-
-
- FileInputStream fis = new FileInputStream(zipFileName);
-
- ZipInputStream zis = new ZipInputStream(fis);
-
- ZipEntry ze = null;
-
-
-
- if (destPath.equals(DOT))
-
- destPath = EMPTY_STRING;
-
-
-
- while ((ze = zis.getNextEntry()) != null) {
-
-
-
-
-
-
-
- if (ze.isDirectory()) {
-
-
-
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing folder:" + ze.getName());
-
- }
-
-
-
-
-
-
-
- String dirName = destPath + ze.getName();
-
-
-
-
-
- File f = new File(dirName);
-
- f.mkdirs();
-
-
-
- if (logger.isDebugEnabled()) {
-
- logger.debug("The folder " + f.getAbsolutePath()
-
- + " is created");
-
- }
-
- }
-
-
-
-
-
-
-
- else {
-
- if (logger.isDebugEnabled()) {
-
- logger.debug("Processing file: " + ze.getName());
-
- }
-
-
-
-
-
-
-
- String fileName = destPath + ze.getName();
-
- File f = new File(fileName);
-
-
-
-
-
- FileOutputStream fos = new FileOutputStream(f);
-
- int tmp = -1;
-
- while ((tmp = zis.read()) != -1) {
-
- fos.write(tmp);
-
- }
-
- zis.closeEntry();
-
- fos.close();
-
-
-
- if (logger.isDebugEnabled()) {
-
- logger.debug("The file " + f.getAbsolutePath()
-
- + " is created");
-
- }
-
- }
-
- }
-
- zis.close();
-
-
-
- } catch (FileNotFoundException ex) {
-
-
-
- if (logger.isErrorEnabled()) {
-
- logger.error("file not found");
-
- }
-
- throw new InvalidFolderZipperException(ZIP_UNZIP_ERROR, ex);
-
-
-
- } catch (IOException ex) {
-
-
-
- if (logger.isErrorEnabled()) {
-
- logger.error("io exception occured");
-
- }
-
-
-
- throw new InvalidFolderZipperException(ZIP_UNZIP_ERROR,
-
- ex);
-
- }
-
- }
-
-
-
- }
(1)在47-93行还是对入参进行严格的检查。
(2)第103行打开了一个ZipInputStream,然后在第115行对于这个zip文件里的所有的条目进行遍历。
(3)第119-159行对于条目是一个目录的情况进行了处理,它必须去相应的创建目录结构
(4)第163-215行对于条目是个文件的情况进行了处理,它打开一个文件输出流然后写这个Zip的文件条目到目标目录下相应的位置。
本文转自 charles_wang888 51CTO博客,原文链接:http://blog.51cto.com/supercharles888/980320,如需转载请自行联系原作者