1. 程式人生 > >Unity3d 檔案的建立,寫入,和讀取

Unity3d 檔案的建立,寫入,和讀取

檔案的建立,寫入,讀取,需要使用流來操作。

示例程式碼如下:

  1. void Start ()
  2.     {
  3.         Createfile (Application.dataPath, "FileName", "TestInfo0");
  4.         Createfile (Application.dataPath, "FileName", "TestInfo1");
  5.         Createfile (Application.dataPath, "FileName", "TestInfo2");
  6.     }
  7.     //檔案的建立,寫入
  8.     void Createfile (string path, string name, string info)
  9.     {
  10.         StreamWriter sw;//流資訊
  11.         FileInfo t = new FileInfo (path + "//" + name);
  12.         if (!t.Exists) {//判斷檔案是否存在
  13.             sw = t.CreateText ();//不存在,建立
  14.         } else {
  15.             sw = t.AppendText ();//存在,則開啟
  16.         }
  17.         sw.WriteLine (info);//以行的形式寫入資訊
  18.         sw.Close ();//關閉流
  19.         sw.Dispose ();//銷燬流
  20.     }

 下面是檔案的讀取例項:

  1. void Start ()
  2.     {
  3.        //讀取檔案
  4.         ArrayList info = LoadFile (Application.dataPath, "FileName");
  5.         foreach (string str in info) {//列印資訊
  6.             Debug.Log (str);
  7.         }
  8.     }
  9.     ArrayList LoadFile (string path, string name)
  10.     {
  11.         StreamReader sr = null;//檔案流
  12.         try {
  13.             //通過路徑和檔名讀取檔案
  14.             sr = File.OpenText (path + "//" + name);
  15.         } catch (Exception ex) {
  16.             return null;
  17.         }
  18.         string line;
  19.         ArrayList arrlist = new ArrayList ();
  20.         while ((line = sr.ReadLine ()) != null) {//讀取每一行加入到ArrayList中
  21.             arrlist.Add (line);
  22.         }
  23.         sr.Close ();
  24.         sr.Dispose ();
  25.         return arrlist;
  26.     }