tar的解壓與壓縮

tar的解壓與壓縮

package com.mtons.mblog.leetcode;


/**
 * import org.apache.tools.tar.TarEntry;
 * import org.apache.tools.tar.TarInputStream;
 * import org.apache.tools.tar.TarOutputStream;
 * 這幾個類對應的maven依賴
 * <dependency>
 * <groupId>org.apache.ant</groupId>
 * <artifactId>ant</artifactId>
 * <version>1.8.0</version>
 * </dependency>
 */

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

import java.io.*;

/**
 * tar的解壓與壓縮
 */
public class TarUtil {

    public static void main(String[] args) throws Exception {
        TarUtil jtar = new TarUtil();
        jtar.tar(new File("C:/Users/Administrator/Desktop/excel模板.png"),"C:/Users/Administrator/Desktop/_refund_bak.tar");
        jtar.unTar(new File("C:/Users/Administrator/Desktop/_refund_bak.tar"), "C:/Users/Administrator/Desktop/");
    }

    /**
     * 歸檔tar文件
     *
     * @throws IOException
     */
    public static File tar(File srcFile, String targetFileName) throws IOException {
        File targetTarFile = new File(targetFileName);// 歸檔後的文件名
        TarOutputStream out = null;
        boolean boo = false;// 是否壓縮成功
        try {
            out = new TarOutputStream(new BufferedOutputStream(new FileOutputStream(targetTarFile)));
            tarNext(srcFile, out, "", true);
            boo = true;
            // 歸檔成功
            return targetTarFile;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException ex) {
                throw new RuntimeException("關閉Tar輸出流出現異常", ex);
            } finally {
                // 清理操作
                if (!boo && targetTarFile.exists())// 歸檔不成功,
                    targetTarFile.delete();
            }
        }
    }

    /**
     * 解壓tar File
     *
     * @param file
     *            要解壓的tar文件對象
     * @param outputDir
     *            要解壓到某個指定的目錄下
     * @throws IOException
     */
    public static File unTar(File file, String outputDir) throws IOException {
        File creatFile = null;
        TarInputStream tarIn = null;
        boolean success = false;
        try {
            if (file.exists() == false) {
                return creatFile;
            }
            tarIn = new TarInputStream(new FileInputStream(file), 1024 * 2);
            createDirectory(outputDir, null);// 創建輸出目錄
            TarEntry entry = null;
            while ((entry = tarIn.getNextEntry()) != null) {
                if (entry.isDirectory()) {// 是目錄
                    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();
                    }
                }
            }
            success = true;
            creatFile = new File(outputDir);
        } finally {
            try {
                if (tarIn != null) {
                    tarIn.close();
                }
                // if(!success){
                // deleteDirectory(new File(outputDir));
                // }
            } catch (IOException ex) {
                throw new IOException("關閉tarFile出現異常", ex);
            }
        }
        return creatFile;
    }

    /**
     * 歸檔tar文件
     *
     * @param file
     *            歸檔的文件對象
     * @param out
     *            輸出tar流
     * @param dir
     *            相對父目錄名稱
     * @param boo
     *            是否把空目錄歸檔進去
     */
    private static void tarNext(File file, TarOutputStream out, String dir, boolean boo) throws IOException {
        if (file.isDirectory()) {// 是目錄
            File[] listFile = file.listFiles();// 得出目錄下所有的文件對象
            if (listFile.length == 0 && boo) {// 空目錄歸檔
                out.putNextEntry(new TarEntry(dir + file.getName() + "/"));// 將實體放入輸出Tar流中
                System.out.println("歸檔." + dir + file.getName() + "/");
                return;
            } else {
                for (File cfile : listFile) {
                    tarNext(cfile, out, dir + file.getName() + "/", boo);// 遞歸歸檔
                }
            }
        } else if (file.isFile()) {// 是文件
            System.out.println("歸檔." + dir + file.getName() + "/");
            byte[] bt = new byte[2048 * 2];
            TarEntry ze = new TarEntry(dir + file.getName());// 構建tar實體
            // 設置壓縮前的文件大小
            ze.setSize(file.length());
            // ze.setName(file.getName());//設置實體名稱.使用默認名稱
            out.putNextEntry(ze);// //將實體放入輸出Tar流中
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(file);
                int i = 0;
                while ((i = fis.read(bt)) != -1) {// 循環讀出並寫入輸出Tar流中
                    out.write(bt, 0, i);
                }
            } catch (IOException ex) {
                throw new IOException("寫入歸檔文件出現異常", ex);
            } finally {
                try {
                    if (fis != null)
                        fis.close();// 關閉輸入流
                    out.closeEntry();
                } catch (IOException ex) {
                    throw new IOException("關閉輸入流出現異常");
                }
            }
        }
    }

    /**
     * 構建目錄
     *
     * @param outputDir
     * @param subDir
     */
    private 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()) {
            file.mkdirs();
        }
    }

    /**
     * 清理文件(目錄或文件)
     *
     * @param file
     */
    private static void deleteDirectory(File file) {
        if (file.isFile()) {
            file.delete();// 清理文件
        } else {
            File list[] = file.listFiles();
            if (list != null) {
                for (File f : list) {
                    deleteDirectory(f);
                }
                file.delete();// 清理目錄
            }
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章