Unity3d 檔案的建立,寫入,和讀取
阿新 • • 發佈:2018-12-23
檔案的建立,寫入,讀取,需要使用流來操作。
示例程式碼如下:
- void Start ()
- {
- Createfile (Application.dataPath, "FileName", "TestInfo0");
- Createfile (Application.dataPath, "FileName", "TestInfo1");
- Createfile (Application.dataPath, "FileName", "TestInfo2");
- }
- //檔案的建立,寫入
- void Createfile (string path, string name, string info)
- {
- StreamWriter sw;//流資訊
- FileInfo t = new FileInfo (path + "//" + name);
- if (!t.Exists) {//判斷檔案是否存在
- sw = t.CreateText ();//不存在,建立
- } else {
- sw = t.AppendText ();//存在,則開啟
- }
- sw.WriteLine (info);//以行的形式寫入資訊
- sw.Close ();//關閉流
- sw.Dispose ();//銷燬流
- }
下面是檔案的讀取例項:
- void Start ()
- {
- //讀取檔案
- ArrayList info = LoadFile (Application.dataPath, "FileName");
- foreach (string str in info) {//列印資訊
- Debug.Log (str);
- }
- }
- ArrayList LoadFile (string path, string name)
- {
- StreamReader sr = null;//檔案流
- try {
- //通過路徑和檔名讀取檔案
- sr = File.OpenText (path + "//" + name);
- } catch (Exception ex) {
- return null;
- }
- string line;
- ArrayList arrlist = new ArrayList ();
- while ((line = sr.ReadLine ()) != null) {//讀取每一行加入到ArrayList中
- arrlist.Add (line);
- }
- sr.Close ();
- sr.Dispose ();
- return arrlist;
- }