Unity:支持Android和IOS文件读取和写入

1、简述

在开发Unity应用程序时,经常会涉及到与设备文件系统进行交互的需求,比如读取配置文件、存储游戏进度等。本文将介绍如何在Unity中实现在Android和iOS平台上读取和写入文件的功能。

2、文件读取

读取文件可以通过FileStream文件流来读取当前的文件

/// <summary>
/// 文件读取数据
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string FileRead(string path)
{
    string data = string.Empty;
    FileInfo t = new FileInfo(path);
    if (!t.Exists)
    {
        return string.Empty;
    }
    try
    {
        FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
        StreamReader sr = new StreamReader(fs, Encoding.UTF8);
        data = sr.ReadToEnd();
        sr.Close();
        fs.Close();
    }
    catch (IOException e)
    {
        Debug.LogError("FileRead: " + e.Message);
    }
    return data;
}

或者 直接通过当前文件来读取:

string fullPath = Path.Combine(Application.persistentDataPath, fileName);
if (File.Exists(fullPath))
{
    string content = File.ReadAllText(fullPath);
    Debug.Log("文件内容:" + content);
}
else
{
    Debug.LogError("文件不存在:" + fullPath);
}

3、文件写入

写入文件可以通过FileStream文件流来写入写入指定路径下:

/// <summary>
/// 文件写入数据
/// </summary>
/// <param name="path"></param>
/// <param name="data"></param>
public static void FileWrite(string path, string data)
{
    try
    {
        FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
        sw.WriteLine(data);
        sw.Close();
        fs.Close();
    }
    catch (Exception ex)
    {
        Debug.LogError(ex);
    }
}

同样我们也可以通过File来直接写入:

string fullPath = Path.Combine(Application.persistentDataPath, fileName);

File.WriteAllText(fullPath, content);
Debug.Log("文件已写入:" + fullPath);

4、文件权限

Unity PC 环境:

public static string BasePath = 
         Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), 
             UnityEngine.Application.productName);

要转为 Unity Android 环境:

public static string BaseAndroidPath =
Path.Combine(Application.temporaryCachePath,UnityEngine.Application.productName);

在Unity IOS 环境:

public static string BaseAndroidPath =
Path.Combine(Application.persistentDataPath,UnityEngine.Application.productName);

备注:Android环境底下Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData这个路径创建文件夹是没有权限可以创建的,只能在Android环境底下Application.temporaryCachePath 的cache目录才可以创建对应存放资源的路径。

5、结论

通过以上代码示例,我们可以在Unity中实现在Android和iOS平台上读取和写入文件的功能。在实际应用中,可以根据具体需求对代码进行进一步优化和扩展。希望本文对你有所帮助!
在这里插入图片描述

  • 1
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

拾荒的小海螺

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

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

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

打赏作者

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

抵扣说明:

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

余额充值