package com.fourdage.dingding.util;

import java.io.*;
import java.util.Properties;
import java.util.zip.GZIPInputStream;

import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarInputStream;


public class ZipUtils {

    /**
     * 构建目录
     * @param outputDir
     * @param subDir
     */
    public static void createDirectory(String outputDir,String subDir){
        File file = new File(outputDir);
        if(!(subDir == null || subDir.trim().equals(""))){//子目录不为空
            file = new File(outputDir + "/" + subDir);
        }
        if(!file.exists()){
            if(!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            file.mkdirs();
        }
    }

    //------------------------------------------------------------------------------------------------------
    /**
     * 解压tar.gz 文件
     * @param file 要解压的tar.gz文件对象
     * @param outputDir 要解压到某个指定的目录下
     * @throws IOException
     */
    public static void unTarGz(File file, String outputDir) throws IOException{
        TarInputStream tarIn = null;
        try{
            tarIn = new TarInputStream(new GZIPInputStream(
                    new BufferedInputStream(new FileInputStream(file))),
                    1024 * 2);

            createDirectory(outputDir,null);//创建输出目录

            TarEntry entry = null;
            while( (entry = tarIn.getNextEntry()) != null ){

                if(entry.isDirectory()){//是目录
                    entry.getName();
                    createDirectory(outputDir,entry.getName());//创建空目录
                }else{//是文件
                    File tmpFile = new File(outputDir + "/" + entry.getName());
                    createDirectory(tmpFile.getParent() + "/",null);//创建输出目录
                    OutputStream out = null;
                    try{
                        out = new FileOutputStream(tmpFile);
                        int length = 0;

                        byte[] b = new byte[2048];

                        while((length = tarIn.read(b)) != -1){
                            out.write(b, 0, length);
                        }

                    }catch(IOException ex){
                        throw ex;
                    }finally{

                        if(out!=null)
                            out.close();
                    }
                }
            }
        }catch(IOException ex){
            throw new IOException("解压归档文件出现异常",ex);
        } finally{
            try{
                if(tarIn != null){
                    tarIn.close();
                }
            }catch(IOException ex){
                throw new IOException("关闭tarFile出现异常",ex);
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        String path = "/data/557662992913661952/";
        String fileName = "copy.tar.gz";
        File f = new File(path);

        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os != null && os.toLowerCase().indexOf("linux") > -1) {
            // linux 执行合并文件命令
            StringBuffer sb = new StringBuffer(" cat ");
            for (int i = 0; i < f.listFiles().length; i++){
                sb.append(f.listFiles()[i].getAbsolutePath());
            }
            sb.append(" >> ").append(path).append(fileName);

            String[] cmd = new String[]{"/bin/sh", "-c", sb.toString()};
            Process process = Runtime.getRuntime().exec(cmd);
            int exitValue = process.waitFor();
            process.getOutputStream().close();
            if (0 == exitValue){
                System.out.println(path+fileName+"：合并完成");
                unTarGz(new File(path + fileName), path);
                System.out.println(path+fileName+"：解压完成");
            }
        } else {
            // windows 执行合并文件命令
            StringBuffer sb = new StringBuffer("cmd.exe /c copy /b ");
            for (int i = 0; i < f.listFiles().length; i++){
                sb.append(f.listFiles()[i].getAbsolutePath());
                if (i != f.listFiles().length -1){
                    sb.append("+");
                }
            }
            sb.append(" ").append(path).append(fileName);
            System.out.println(sb.toString());
            Process process = Runtime.getRuntime().exec(sb.toString());
            int exitValue = process.waitFor();
            process.getOutputStream().close();
            if (0 == exitValue){
                System.out.println(path+fileName+"：合并完成");
                unTarGz(new File(path + fileName), path);
                System.out.println(path+fileName+"：解压完成");
            }
        }
    }
}
