Unity拷贝文件到指定路径

主要用于将StreamingAssets文件拷贝到persistentDataPath路径下应为比较简单我就直接上代码了。

 

1.使用WWW方式拷贝文件(www API即将要弃用)

using System.IO;
using UnityEngine;
using System;

namespace Mx.Util
{
    /// <summary>拷贝文件</summary>
    public class CopyFiles
    {
        /// <summary>
        /// 拷贝文件到指定路径(需要加文件后缀)
        /// </summary>
        /// <param name="pStrFilePath">需要拷贝文件的路径</param>
        /// <param name="pPerFilePath">拷贝到路径</param>
        /// <param name="finish">结束回调</param>
        public static void Copy(string pStrFilePath, string pPerFilePath, Action<string> finish = null)
        {
            if (string.IsNullOrEmpty(pStrFilePath) || string.IsNullOrEmpty(pPerFilePath))
            {
                Debug.LogWarning("CopyFiles/Copy/" + "copy file wrong! file path is null!");
                return;
            }

            if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXEditor)
            {
                pStrFilePath = @"file://" + pStrFilePath;
            }

            else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            {
                pStrFilePath = @"file:///" + pStrFilePath;
            }

            string[] tempPerFilePathArr = pPerFilePath.Split('/');
            string tempPerFilePath = pPerFilePath.Replace(tempPerFilePathArr[tempPerFilePathArr.Length - 1], null);
            if (!Directory.Exists(tempPerFilePath)) Directory.CreateDirectory(tempPerFilePath);

            WWW ww = new WWW(pStrFilePath);

            while (!ww.isDone) { }
            if (string.IsNullOrEmpty(ww.error))
            {
                var buffer = ww.bytes;
                if (File.Exists(pPerFilePath))
                    File.Delete(pPerFilePath);
                var ws = File.Create(pPerFilePath);
                ws.Write(buffer, 0, buffer.Length);
                ws.Close();

                if (finish != null) finish(null);

                Debug.Log("CopyFiles/Copy/" + "copy file success:" + pPerFilePath);
            }
            else
            {
                if (finish != null) finish(ww.error);

                Debug.LogWarning("CopyFiles/Copy/" + "copy file wrong !!!!   " + ww.error);
            }
            ww.Dispose();
        }
    }
}

2.使用UnityWebRequest方式拷贝文件

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace Mx.Utils
{
    /// <summary>拷贝文件</summary>
    public class CopyFiles : MonoBehaviour
    {
        private Dictionary<string, UnityWebRequest> downReqMap = new Dictionary<string, UnityWebRequest>();
        private Dictionary<string, Coroutine> coroutines = new Dictionary<string, Coroutine>();

        /// <summary>拷贝(同步的方式拷贝文件,当拷贝大文件的时候会存在卡顿问题)</summary>
        public static void Copy(string inPath, string outPath, Action<float> progress = null, Action<UnityWebRequest> callback = null)
        {
            outPath = outPath.Replace("file://", null);
            if (Application.platform != RuntimePlatform.Android) inPath = @"file://" + inPath;

            copy(inPath, outPath, progress, callback);
        }

        /// <summary>异步拷贝(适合拷贝大文件)</summary>
        public void CopyAsyn(string inPath, string savePath, Action<float> progress = null, Action<UnityWebRequest> callback = null)
        {
            savePath = savePath.Replace("file://", null);
            if (Application.platform != RuntimePlatform.Android) inPath = @"file://" + inPath;

            if (!downReqMap.ContainsKey(inPath))
            {
                coroutines.Add(inPath, StartCoroutine(copyAsyn(inPath, savePath, progress, callback)));
            }
        }

        private static void copy(string url, string outPath, Action<float> progress, Action<UnityWebRequest> callback)
        {
            var uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);
            uwr.downloadHandler = new DownloadHandlerFile(outPath);
            uwr.SendWebRequest();

            while (!uwr.isDone)
            {
                if (progress != null) progress(uwr.downloadProgress);
            }

            if (callback != null) { callback(uwr); }
        }

        private IEnumerator copyAsyn(string url, string savePath, Action<float> progress, Action<UnityWebRequest> callback)
        {
            var uwr = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);

            uwr.downloadHandler = new DownloadHandlerFile(savePath);
            uwr.SendWebRequest();

            downReqMap.Add(url, uwr);

            while (!uwr.isDone)
            {
                yield return new WaitForEndOfFrame();
                if (progress != null) progress(uwr.downloadProgress);
                yield return null;
            }

            if (callback != null) { callback(uwr); }
            Dispose(url);
        }

        public void Dispose(string url)
        {
            if (coroutines.ContainsKey(url))
            {
                if (coroutines[url] != null) StopCoroutine(coroutines[url]);
                coroutines.Remove(url);
            }

            if (downReqMap.ContainsKey(url))
            {
                if (downReqMap[url] != null) downReqMap[url].Abort();
                if (downReqMap[url] != null) downReqMap[url].Dispose();
                downReqMap.Remove(url);
            }
        }

        public void DisposeAll()
        {
            foreach (Coroutine ct in coroutines.Values) { if (ct != null) StopCoroutine(ct); }
            coroutines.Clear();

            foreach (var item in downReqMap.Values)
            {
                if (item != null) item.Abort();
                if (item != null) item.Dispose();//释放
            }
            downReqMap.Clear();
        }

        private void OnDestroy()
        {
            DisposeAll();
        }
    }
}

 

Unity QQ交流群:299412191 欢迎对Unity感兴趣的同学加入.

    原文作者:DaLiangChen
    原文地址: https://blog.csdn.net/a451319296/article/details/104039087
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞