package com.dxhy.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;

/**
 * 7z文件操作工具类
 *
 * @author jiaohongyang
 */
@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaClassNamingShouldBeCamel"})
public class SevenZFileUtil {

    /**
     * @param orgPath
     *            源压缩文件地址
     * @param tarpath
     *            解压后存放的目录地址
     * @throws IOException
     *             异常
     *
     */
    public static void unSevenZFile(String orgPath, String tarpath) throws IOException {

        File orgFile = new File(orgPath);
        SevenZFile zFile = new SevenZFile(orgFile);
        SevenZArchiveEntry entry = zFile.getNextEntry();
        while (entry != null) {
            if (entry.isDirectory()) {
                new File(tarpath + entry.getName()).mkdirs();
                entry = zFile.getNextEntry();
                continue;
            }
            FileOutputStream out = new FileOutputStream(tarpath + entry.getName());
            byte[] content = new byte[(int)entry.getSize()];
            zFile.read(content, 0, content.length);
            out.write(content);
            out.close();
            entry = zFile.getNextEntry();
        }
        zFile.close();
        // 删除本地文件，防止服务器空间不足
        orgFile.delete();
    }

    /**
     * 获取某个路径下第一个文件的名称
     *
     * @param filePath
     *            文件路径
     *
     */
    public static String getFirstFileName(String filePath) {
        File file = new File(filePath);
        String[] fileList = file.list();
        File readfile = new File(filePath + "/" + fileList[0]);
        return readfile.getName();
    }

}
