Unity读取IOS平台文件

本例测试在IOS端读取 .txt 文件

在开发时,需要在IOS端读取的文件文件一定要放在 “StreamingAssets” 文件夹下(在安装时IOS会自动将StreamingAssets文件夹下的文件放到相应的平台路径),没有该文件夹自己在 Assets下创建


using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.IO;

public class WriteReadTxt : MonoBehaviour
{
    private string path = "";
    private static string context = "";

    void Start()
    {
        
#if UNITY_IPHONE
        path = Application.streamingAssetsPath;  //获取文件路径
        //path = Application.dataPath +"/Raw";   //获取文件路径
#elif UNITY_EDITOR
        path = Application.dataPath + "/StreamingAssets";  //获取文件路径
#endif
    }

    void OnGUI()
    {
        if (GUI.Button(new Rect(50, 50, 200, 50), "ReadAA"))
        {
            ReadTxtAAA( path, "ABC.txt");
        }

        if (GUI.Button(new Rect(50, 150, 200, 50), "ReadBBB"))
        {
            ReadTxtBBB( path, "ABC.txt");
        }

        if (GUI.Button(new Rect(50, 250, 200, 50), "Clear"))
        {
            context = "";
        }

        GUI.Label(new Rect(50, 300, 300, 150), "path  " + path);
        GUI.Label(new Rect(50, 500, 500, 500), "content   : " + context);
    }
    
    //参数1 路径名,参数2 文件名 要带后缀
    private void ReadTxtAAA(string pat, string txtName)
    {
        string sss = pat + "//" + txtName;
        StreamReader sr = null;
        try
        {
            sr = File.OpenText(sss); //打开文件
        }
        catch
        {
            return;
        }

        context = sr.ReadToEnd(); //读取到文件最后
        sr.Close();
        sr.Dispose();
    }

    //参数1 路径,参数2 文件名 要带后缀
    private void ReadTxtBBB(string pat, string txtName)
    {
        string sss = pat + "//" + txtName;
        //判断文件是否存在
        if (!File.Exists(sss))
        {
            context = "!Exists" + sss;
            return;
        }

        try
        {
            //打开流文件
			StreamReader sr = File.OpenText(sss); 
            //读取到文件最后
            context = sr.ReadToEnd();
            sr.Close();
			sr.Dispose();
        }
        catch (Exception e)
        {
			throw(e);//抛出异常
        }
    }

    // 下面方法总是出问题, 判断文件是否存在没问题,在读取的时候有问题,
    //由于对 StreamReader 不是很了解
    //具体问题还没有做深入研究,下方法有待改进
    /*
    private void ReadTxtCCC(string pat, string txtName)
    {
        string sss = pat + "//" + txtName;
        if (!File.Exists(sss))
        {
            context = "!Exists" + sss;
            return;
        }

        try
        {
            FileStream file = new FileStream(sss, FileMode.Open);
            StreamReader sr = new StreamReader(file);
            context = sr.ReadToEnd();
            sr.Close();
            file.Close();
            sr.Dispose();
        }
        catch (Exception e)
        {
            throw (e);
        }
    }
     * */

}


你可能感兴趣的:(Unity)