1. 程式人生 > >unity ZIP壓縮解壓 Byte[]資料壓縮解壓

unity ZIP壓縮解壓 Byte[]資料壓縮解壓

在網上看了一些相關資源,都比較散;為了方便以後檢視,我就整理一下 記性比較差長時間不接觸說不定就忘了 

我這給一個ICSharpCode.SharpZipLib的下載連結:https://pan.baidu.com/s/1o8QcYkq

朋友們也可以百度找最新的下載一個就行 

public class ZIP
{
    private static ZIP instance;
    public static ZIP Instance
    {
        get {
            if (instance == null)
                instance = new ZIP(); 
            return instance;
        }
    }


    // Use this for initialization  
    void Start()
    {


    }
    /// <summary>
    /// 解壓zip
    /// </summary>
    /// <param name="path"></param>
    public void DecompressionZIP(string path, string dirPath, Action<bool> callback = null)
    {
        Main._instance.StartCoroutine(UnzipWithPath(path, dirPath, callback));
    }


    private int totalCount;
    private int doneCount;
    private int indicatorStep = 1;
    public IEnumerator UnzipWithPath(string path, string dirPath, Action<bool> callback = null)
    {
        //將codepage編碼設定對應的字元編碼
        ZipConstants.DefaultCodePage = Encoding.UTF8.CodePage;
        //這是根目錄的路徑  
        //ZipEntry:檔案條目 就是該目錄下所有的檔案列表(也就是所有檔案的路徑)  
        ZipEntry zip = null;
        //輸入的所有的檔案流都是儲存在這裡面的  
        ZipInputStream zipInStream = null;
        //讀取檔案流到zipInputStream  
        zipInStream = new ZipInputStream(File.OpenRead(path));
        bool isError = false;
        while ((zip = zipInStream.GetNextEntry()) != null)
        {
            //Debug.Log("name is:" + zip.Name + " zipStream " + zipInStream);
            bool error = UnzipFile(zip, zipInStream, dirPath);
            if (error)
            {
                UIUtils.LogError("error:錯誤!!!!!!!!!");
                if (callback != null)
                    callback(false);
                isError = true;
                break;
            }
            doneCount++;
            if (doneCount % indicatorStep == 0)
                yield return new WaitForEndOfFrame();
        }
        try
        {
            zipInStream.Close();
        }
        catch (Exception ex)
        {
            UIUtils.Log("UnZip Error");
            throw ex;
        }
        if (!isError)
        {
            if (callback != null)
                callback(true);
            //解壓完成後刪除zip
            File.Delete(path);
            UIUtils.Log("解壓完成:" + path);
        }
    }
    static bool UnzipFile(ZipEntry zip, ZipInputStream zipInStream, string dirPath)
    {
        try
        {
            //檔名不為空  
            if (!string.IsNullOrEmpty(zip.Name))
            {
                string filePath = dirPath;
                filePath += ("/" + zip.Name);


                if (BundleManager.Instance.CheckLoadAssetBundle(filePath))
                    UIUtils.LogError("刪除更新包資源");
                filePath = filePath.Replace("//", "/");
                UIUtils.LogError(filePath + "==" + zip.Name);
                //如果是一個新的檔案路徑 這裡需要建立這個檔案路徑  
                if (IsDirectory(filePath))
                {//是資料夾則不需要處理
                    if (!Directory.Exists(filePath)) //沒有則夾建立資料夾
                    {
                        UIUtils.LogError("建立Directory" + filePath);
                        Directory.CreateDirectory(filePath);
                    }
                    UIUtils.LogError("這是資料夾");
                }
                else
                {
                    //找到資料夾
                    string directory = GetDirectory(filePath);
                    UIUtils.LogError("得到檔案" + directory);
                    if (!string.IsNullOrEmpty(filePath))
                    {//檢測是否有資料夾
                        if (!Directory.Exists(directory)) //沒有則夾建立資料夾
                        {
                            UIUtils.LogError("建立Directory" + directory);
                            Directory.CreateDirectory(directory);
                        }
                    }
                    FileStream fs = null;
                    //當前資料夾下有該檔案  刪掉  重新建立  
                    UIUtils.LogError("檢測檔案" + filePath);
                    if (File.Exists(filePath))
                    {
                        UIUtils.LogError("Delete Files:::");
                        File.Delete(filePath);
                    }
                    UIUtils.LogError("建立檔案" + filePath);
                    fs = File.Create(filePath);
                    int size = 2048;
                    byte[] data = new byte[2048];
                    //每次讀取2MB  直到把這個內容讀完  
                    while (true)
                    {
                        size = zipInStream.Read(data, 0, data.Length);
                        //小於0, 也就讀完了當前的流  
                        if (size > 0)
                        {
                            fs.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    fs.Close();
                }
            }
            return false;
        }
        catch (Exception e)
        {
            UIUtils.LogError(e);
            return true;
        }
    }


    /// <summary>  
    /// 目錄檔案  
    /// </summary>  
    /// <param name="path"></param>  
    /// <returns></returns>  
    static string GetDirectory(string path)
    {
        for (int i = path.Length - 1; i >= 0; --i)
        {
            if (path[i] == '/')
            {
                string stringPath = new string(path.ToCharArray(), 0, i);
                return stringPath.ToString();
            }
        }
        return null;
    }
    /// <summary>  
    /// 是否是目錄資料夾  
    /// </summary>  
    /// <param name="path"></param>  
    /// <returns></returns>  
    static bool IsDirectory(string path)
    {
        if (path[path.Length - 1] == '/')
        {
            return true;
        }
        return false;
    }
    /// <summary>
    /// 壓縮
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public static string CompressStringToString(string param)
    {
        byte[] data = Encoding.UTF8.GetBytes(param);
        return CompressByteToString(data);
    }
    public static string CompressByteToString(byte[] inputBytes)
    {
        return Convert.ToBase64String(CompressByteToByte(inputBytes));
    }
    public static byte[] CompressByteToByte(byte[] inputBytes)
    {
        MemoryStream ms = new MemoryStream();
        Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
        try
        {
            stream.Write(inputBytes, 0, inputBytes.Length);
        }
        finally
        {
            stream.Close();
            ms.Close();
        }
        return ms.ToArray();
    }
    /// <summary>
    /// 解壓
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public static string DecompressStringToString(string param)
    {
        byte[] buffer = Convert.FromBase64String(param);
        return DecompressByteToString(buffer) ;
    }
    public static string DecompressByteToString(byte[] inputBytes)
    {
        string commonString = "";
        MemoryStream ms = new MemoryStream(inputBytes);
        Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
        //這裡要指明要讀入的格式,要不就有亂碼
        StreamReader reader = new StreamReader(sm, Encoding.UTF8);
        try
        {
            commonString = reader.ReadToEnd();
        }
        finally
        {
            sm.Close();
            ms.Close();
        }
        return commonString;
    }
    public static byte[] DecompressByteToByte(byte[] inputBytes)
    {
        MemoryStream ms = new MemoryStream(inputBytes);
        Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
        byte[] data = new byte[sm.Length];
        int count = 0;
        MemoryStream re = new MemoryStream();
        while ((count = sm.Read(data, 0, data.Length)) != 0)
        {
            re.Write(data, 0, count);
        }
        sm.Close();
        ms.Close();
        return re.ToArray();
    }
    public static byte[] DecompressStringToByte(string param)
    {
        byte[] buffer = Convert.FromBase64String(param);
        MemoryStream ms = new MemoryStream(buffer);
        Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
        byte[] data = new byte[sm.Length];
        int count = 0;
        MemoryStream re = new MemoryStream();
        //這裡要指明要讀入的格式,要不就有亂碼
        StreamReader reader = new StreamReader(sm, Encoding.UTF8);
        try
        {
            while ((count = sm.Read(data, 0, data.Length)) != 0)
            {
                re.Write(data, 0, count);
            }
        }
        finally
        {
            sm.Close();
            ms.Close();
        }
        return re.ToArray();
    }
}