ファイル入出力

このページはVersion 5.6.1f1 Personalを対象としています。

更新履歴

参考URL

概要

このページでは「.csv」などのテキストアセットをResourcesから読み込んだり、 Application.persistantDataPathに読み書きするやり方をまとめています。

テキストアセットをResourcesから読み込む。

    //テキストを「Assets/Resources/path」から読み込む。拡張子はいらない
    public static string LoadTextFromResources(string path)
    {
        return (Resources.Load(path) as TextAsset).text;
    }

上のコードはテキストアセットをResourcesから読み込むコードです。 pathはフォルダは「/」で区切り、ファイルの拡張子は省略します。 ただし、ファイル自体の拡張子は 「.txt、.html、.htm、.xml、.bytes、.json、.csv、.yaml、.fnt」 のいずれかである必要があります。 用途としてはcsv形式のアイテムデータなどを、 Resourcesフォルダに入れて、 そこから読み込んで使うなどに使います。

テキストファイルをApplication.persistantDataPathに読み書きする。

    //テキストを「Application.persistentDataPath/path」へ保存する。
    public static void SaveTextToPersistent(string path, string text)
    {
        string filePath = Application.persistentDataPath + "/" + path;
        string directoryPath = Path.GetDirectoryName(filePath);
        //フォルダがない場合作成する
        if(!Directory.Exists(directoryPath))
        {
            try
            {
                Directory.CreateDirectory(directoryPath);
            }
            catch (IOException exc)
            {
                Debug.Log(exc.Message); //MessageBox.Show(exc.Message));
            }
        }

        FileStream fs;

        try
        {
            fs = new FileStream(
                filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite
                );
        }
        catch (IOException exc)
        {
            Debug.Log(exc.Message); //MessageBox.Show(exc.Message));
            return;
        }
        StreamWriter sw = new StreamWriter(fs);

        try
        {
            sw.Write(text);
        }
        catch (IOException exc)
        {
            Debug.Log(exc.Message); //MessageBox.Show(exc.Message));
        }

        sw.Close();

    }

    //テキストを「Application.persistentDataPath/path」から読み込む。
    public static string LoadTextFromPersistent(string path)
    {
        string filePath = Application.persistentDataPath + "/" + path;

        FileStream fs;
        string text;

        try
        {
            fs = new FileStream(
                filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite
            );
        }
        catch (IOException exc)
        {
            Debug.Log(exc.Message); //MessageBox.Show(exc.Message));
            return "";
        }
        StreamReader sr = new StreamReader(fs);

        try
        {
            text = sr.ReadToEnd();
        }
        catch (IOException exc)
        {
            Debug.Log(exc.Message); //MessageBox.Show(exc.Message));
            return "";
        }

        sr.Close();

        return text;
    }

上のコードはテキストファイルをApplication.persistantDataPathに読み書きするコードです。 Resourcesから読み込む場合と異なり、拡張子は指定する必要があります。 Application.persistantDataPathは私の環境では、 「C:/Users/ユーザー名/AppData/LocalLow/DefaultCompany/プロジェクト名」(AppDataフォルダは隠しファイル) でした。 用途としてはcsv形式のセーブデータを保存・読込するなどに使います。

戻る

inserted by FC2 system