读取和保存txt文件

来源:互联网 发布:淘宝加入购物车看不到 编辑:程序博客网 时间:2024/04/19 21:01

涉及知识点

  1. 读取文件内容;
  2. 创建文件夹和文件,并写入内容;
  3. 以覆盖的方式写入内容,以添加的方式写入内容;

读取和保存txt文件源码

using UnityEngine;

using System.Text.RegularExpressions;
using System;
using System.Net;
using System.Text;
using System.Threading;
using System.IO;
using UnityEngine.UI;


public class ReadAndSaveText : MonoBehaviour
{
    public InputField input;
    public Toggle isAdd;
    public Text showSaveData;
    public Text showReadData;


    private WebClient myWebClient = new WebClient();
    private string url = "http://www.163.com";
    private string userDocPath;
    private string directory;
    private string filePath;    


    protected void Start()
    {
#if UNITY_STANDALONE_LINUX
        userDocPath = Environment.GetEnvironmentVariable("HOME");//home目录
#elif UNITY_STANDALONE_WIN
        userDocPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//文档目录
#endif    
        directory = userDocPath + "/.Test";
        filePath = directory + "/Test.txt";
        Debug.Log("Save data directory: " + directory);  
    }


    public void ReadData()
    {
        string readData = null;
        if (Directory.Exists(directory) && File.Exists(filePath))
        {
            using (StreamReader read = new StreamReader(filePath, Encoding.Default))
            {
                readData = read.ReadToEnd();
            }            
        }


        showReadData.text = "读取内容:\n" + readData;
    }


    public void SaveData()
    {
        string data = input.text;    


        Debug.Log("Saving data file.");


        if (!Directory.Exists(directory))
            Directory.CreateDirectory(directory);


        if (!File.Exists(filePath))
        {
            Debug.Log("Creating new data file.");


            //创建文件并写入内容,同时换行
            FileStream fs = new FileStream(filePath, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(data);


            sw.Flush();
            sw.Close();
            fs.Close();


            showSaveData.text += "\n" + data;
        }
        else
        {
            if (!isAdd.isOn)
            {
                //覆盖内容,同时换行
                using (StreamWriter sw = new StreamWriter(filePath))
                {
                    sw.WriteLine(data);
                }


                showSaveData.text = "保存内容:\n" + data;
            }
            else
            {
                //在已有的文本后添加新的内容,同时换行
                using (StreamWriter sw = File.AppendText(filePath))
                {
                    sw.WriteLine(data);
                }


                showSaveData.text += "\n" + data;
            }
        }


        Debug.Log("Save data success.");
    }   

}

文章仅供学习和参考!如有错误请指正!