java 的Zip文件压缩与解压

zip 压缩文件

/**
*zipFile 压缩文件路径
*fileItem 被压缩的文件
**/
public static File zipFiles(File zipFile,File... fileItem) throws FileNotFoundException{
		ZipOutputStream zos = null;
		try {
			final String fileName = zipFile.getName();
			// 创建一个新的压缩输出流
			zos = new ZipOutputStream(new FileOutputStream(zipFile));
			//设置文件注释
			zos.setComment(fileName);
			//文件流
			InputStream input = null;
			for (File itemFile : fileItem) {
				if( itemFile == null ){
					//跳过为空的文件
					continue;
				}
				if( !itemFile.exists() ){
					//跳过不存在的文件
					LOGGER.warn("[{}]添加压缩时,文件{}不存在",fileName,itemFile.getPath());
					continue;
				}
				try {
					//文件输入流
					input = new FileInputStream(itemFile);
					String itemFileName = itemFile.getName();
					//从指定的压缩项的字段创建一个新的压缩条目。 ->new ZipEntry(itemFileName)
					//开始编写一个新的压缩文件条目,并将流定位到输入数据的开始处。
					// 如果仍然有效,关闭当前条目。如果没有指定输入的压缩方法,将使用默认的压缩方法,
					// 如果条目没有设置修改时间,当前的时间将被使用。
					zos.putNextEntry(new ZipEntry(itemFileName));
					int temp = 0;
					//下一个数据字节,或 -1如果到达文件的结尾。 ->input.read();
	                while((temp = input.read()) != -1){  
	                	zos.write(temp);  
	                }
				} catch (Exception e) {
					LOGGER.error("添加文件到压缩包失败" + itemFile.getName(), e );
				} finally {
	                close(input);
				}
			}
		} finally {
            close(zos);
		}
		return zipFile;
	}

ZIP解压

1.解压方法

 /**
     * ZIP包的解压
     *
     * @param zipSourceFile     zip源文件
     * @param unPackFolder      解压后的目标文件夹
     * @param currentTimeMillis 文件名组成字段(时间)
     * @return
     */
    public static List<File> unPackZip(File zipSourceFile, String unPackFolder, String currentTimeMillis) {
        ZipFile zipFile = null;
        List<File> files = new ArrayList<>();
        try {
            zipFile = new ZipFile(zipSourceFile);
            File targetFile;
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String targetPath = unPackFolder + File.separator + entry.getName();
                // 如果是文件夹,就创建个文件夹
                if (entry.isDirectory()) {
                    targetFile = dirFile(targetPath, true, currentTimeMillis);
                } else {
                    targetFile = pathToFile(targetPath, true, currentTimeMillis);
                    if (targetFile == null) {
                        continue;//文件无法创建,跳过解压操作
                    }
                    // 将压缩文件内容写入到这个文件中
                    InputStream is = zipFile.getInputStream(entry);
                    org.apache.commons.io.FileUtils.copyInputStreamToFile(is, targetFile);
                    files.add(targetFile);
                }
            }
            return files;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            log.error("解压压缩文件失败" + zipSourceFile.getName(), e);
            throw new TipException("unzip error from ZipUtils", e);
        } finally { //最后关闭文件流
            FileUnzipUtils.close(zipFile);
        }
        return null;
    }

 /**
     * 关闭IO流
     *
     * @param ioObj IO流对象
     */
    public static void close(Closeable ioObj) {
        if (ioObj != null) {
            try {
                ioObj.close();
            } catch (IOException e) {//忽略异常
                //LOGGER.error(e.getMessage());
            }
        }
    }

    /**
     * 获取指定文件夹的文件对象,可以用来判断文件夹是否存在
     *
     * @param path              指定路径(这个应该是个绝对路径,否则会提示不存在)
     * @param isCreater         如果参数为true,如果目录path不存在则创建,为false,不进行操作
     * @param currentTimeMillis 文件名组成字段(时间)
     * @return 返回文件夹对象
     */
    public static File dirFile(String path, boolean isCreater, String currentTimeMillis) {
        if (oConvertUtils.isEmpty(path)) {
            return null;
        }
        //解压源文件的名称路径
        File file = new File(path);
        //解压添加一个时间的文件字段
        File file1 = new File(file.getPath() + currentTimeMillis);
//        //首先确保是个绝对类路径
        if (file1.isAbsolute()) {
            try {
                //已存在
                if (file1.exists()) {
                    return file;
                }
                //不存在则创建
                if (isCreater && file1.mkdirs()) {
                    //创建成功
                    return file;
                }
            } catch (Exception e) {
                //如果创建失败,输出日志
                log.error("路径不存在" + path, e);
            }
        }
        return null;
    }

    /**
     * 获取指定路径的文件对象
     *
     * @param path              指定文件所在路径
     * @param isCreater         如果参数为true,如果不存在则创建,为false,不进行操作
     * @param currentTimeMillis 文件名组成字段(时间)
     * @return 返回文件对象
     */
    public static File pathToFile(String path, boolean isCreater, String currentTimeMillis) {
        if (oConvertUtils.isEmpty(path)) {
            return null;
        }
        //替换成一个追加时间的文件路径。
        File file = new File(path.replace("/", currentTimeMillis + "/"));
        //判断文件是否存在
        if (file.exists()) {
            return file;
        }
        if (isCreater) {
            try {
                //确保上级目录存在
                File parentDir = file.getParentFile();
                //判断上级目不存在,并却创建目录成功!
                if (!parentDir.exists() && file.getParentFile().mkdirs()) {
                    if (file.createNewFile()) {
                        return file;
                    }
                }
                //表示上级目录存在
                else if (parentDir.exists()) {
                    if (file.createNewFile()) {
                        return file;
                    }
                } else {
                    log.warn("上级目录不存在" + path);
                }
            } catch (Exception e) {
                log.error("文件写入失败" + path, e);
            }
        }
        return null;
    }

2.制定文件删除

/**
     * 删除指定的文件
     *
     * @param strFileName
     *            指定绝对路径的文件名
     * @return 如果删除成功true否则false
     */
    public static boolean delete(String strFileName) {
        File fileDelete = new File(strFileName);
        if (!fileDelete.exists() || !fileDelete.isFile()) {
            log.warn("操作失败: {}不存在!",strFileName);
            return false;
        }
        return fileDelete.delete();
    }


版权声明:本文为qq_44805463原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。