Unity编程笔录--程序内压缩和解压

前言:

在Unity中,有可能需要用到文件的自动压缩和解压,大多数情况下解压用到的比较多。此文解决单个文件的压缩,文件夹内的所有文件压缩,解压文件夹


准备资料:

Unity使用的压缩和解压使用的是一个叫做 ICSharpCode.SharpZipLib.dll 的文件,该文件的下载地址为:
链接:http://pan.baidu.com/s/1nvCYjrF 密码:bvvd

下载之后放在Unity工程里面的Plugins文件夹下即可,本人已经过Android和iOS测试,完全可以使用。


正文:

首先贴上本人使用到的压缩解压的脚本文件:

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using ICSharpCode.SharpZipLib.Checksums;
public class ABZipFileUtil
{
    public const int BUFFER_SIZE = 2048;

    #region 压缩等级

    // 0 - store only to 9 - means best compression
    public enum CompressLevel
    {
        Store = 0,
        Level1,
        Level2,
        Level3,
        Level4,
        Level5,
        Level6,
        Level7,
        Level8,
        Best
    }
    #endregion
    /// 
    /// 压缩文件
    /// 
    /// 源文件名称
    /// 压缩包文件名称
    /// 压缩包文件内容名称
    public static void ZipCompressFiles(List sourcefilenames, string zipfilename)
    {
        FileStream baseOutputStream = File.Create(zipfilename);
        ZipOutputStream zipOutputStream = new ZipOutputStream(baseOutputStream);

        foreach (string item in sourcefilenames)
        {
            FileStream fileStream = File.OpenRead(item);
            byte[] array = new byte[fileStream.Length];
            fileStream.Read(array, 0, array.Length);
            fileStream.Close();
            ZipEntry entry = new ZipEntry(Path.GetFileName(item));
            zipOutputStream.PutNextEntry(entry);
            zipOutputStream.SetLevel(Convert.ToInt32(CompressLevel.Level6));
            zipOutputStream.Write(array, 0, array.Length);
        }
        zipOutputStream.Finish();
        zipOutputStream.Close();
#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
    }
    /// 
    /// 解压文件
    /// 
    /// 压缩包文件全路径
    /// 压缩保存路径,如果没有值则默认保存在同级目录下
    public static string ZipDecompressFile(string zipFile, string targetPath = null)
    {
        string directoryName = targetPath;
        //如果解压目录不存在,则默认解压到同级目录下
        if (targetPath == null)
        {
            directoryName = Path.Combine(Path.GetDirectoryName(zipFile), Path.GetFileNameWithoutExtension(zipFile)).Replace("\\", "/") + "/";
        }

        if (!Directory.Exists(directoryName))
        {
            Directory.CreateDirectory(directoryName);
        }
        string currentDirectory = directoryName;
        byte[] data = new byte[BUFFER_SIZE];
        int size = BUFFER_SIZE;
        ZipEntry theEntry = null;
        using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFile)))
        {
            while ((theEntry = s.GetNextEntry()) != null)
            {
                if (theEntry.Name != string.Empty)
                {

                    if (theEntry.Name.Contains("/"))
                    {
                        string path = Path.GetDirectoryName(currentDirectory + theEntry.Name);
                        //说明包含多层路径
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                    }

                    if (!File.Exists(currentDirectory + theEntry.Name))
                    {
                        using (FileStream streamWriter = File.Create(currentDirectory + theEntry.Name))
                        {
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size <= 0)
                                {
                                    break;
                                }
                                streamWriter.Write(data, 0, size);
                            }
                            streamWriter.Close();
                        }
                    }


                }

            }
            s.Close();
        }
        
        // File.Delete(zipFile);
#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
        return directoryName;
    }


    /// 
    /// 创建多级目录的压缩文件
    /// 
    /// 文件夹路径
    /// 压缩包文件夹路径
    public static void ZipCreateMuilFiles(string dirPath, string zipFilePath)
    {
        if (!Directory.Exists(dirPath))
        {
            return;
        }
        ZipOutputStream stream = new ZipOutputStream(File.Create(zipFilePath));
        stream.SetLevel(Convert.ToInt32(CompressLevel.Level6)); // 压缩级别 0-9  
        byte[] buffer = new byte[BUFFER_SIZE]; //缓冲区大小  
        string[] filenames = Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories);
        foreach (string file in filenames)
        {
            if (Path.GetExtension(file) == ".meta")
            {
                continue;
            }
            ZipEntry entry = new ZipEntry(file.Replace(dirPath, "").Replace("\\", "/"));
            entry.DateTime = DateTime.Now;
            stream.PutNextEntry(entry);
            using (FileStream fs = File.OpenRead(file))
            {
                int sourceBytes;
                do
                {
                    sourceBytes = fs.Read(buffer, 0, buffer.Length);
                    stream.Write(buffer, 0, sourceBytes);
                } while (sourceBytes > 0);
            }

        }

        stream.Finish();
        stream.Close();
#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
    }



}


不包含多级目录的文件压缩方式调用方式如下:
 ABZipFileUtil.ZipCompressFiles(new List()
                {
                   [文件全路径],[文件全路径]
                }, [压缩包文件保存路径]);

包含多级目录的文件夹压缩方式调用方法如下:
   ABZipFileUtil.ZipCreateMuilFiles([需要压缩的文件夹全路径], [压缩包保存的路径]);


解压压缩包调用方法如下:
     ABZipFileUtil.ZipDecompressFile([压缩包文件的全路径]);

PS:目前压缩方式都保存的为zip文件,本人没有试其他类型的文件,解压不区分压缩包为单级目录压缩包还是多级目录压缩包,默认就解压为同样的层级关系文件。








你可能感兴趣的:(Unity编程笔录)