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感兴趣的同学加入.

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DaLiangChen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值