1. 程式人生 > 實用技巧 >第47天檔案操作、序列化、本地檔案和巨集

第47天檔案操作、序列化、本地檔案和巨集

檔案操作

資料夾/檔案操作

名稱空間:System.IO

I: Input

O: output

IO流:輸入輸出流

路徑

相對路徑

相對於某一個資料夾的路徑,無碟符,如:"桌面\學習資料.txt".

Resources.Load(相對路徑)

絕對路徑

帶有碟符的,如:"C:\桌面\學習資料.txt";"C:/桌面/學習資料.txt"; "C:/桌面\學習資料.txt"; (windows中正反斜槓都能辨認出來)

IO操作一般使用都是絕對路徑

資料夾操作(Directory)

Exists

判斷某個資料夾是否存在: Directory.Exists(string path);

Delete(刪除資料夾)

Directory.Delete(路徑, 是否遞迴刪除資料夾內所有東西 );

第二個引數:是否遞迴將其資料夾中的所有子資料夾或子檔案全部刪除

該刪除方式在回收站是找不到的

CreateDirectory(建立資料夾)

Directory.CreateDirectory(路徑/資料夾名)

Move

1.移動資料夾

Directory.Move(原始檔夾路徑,目標資料夾路徑);

2.改名

通過Move方法可以實現資料夾重新命名

Directory.Move(原始檔夾路徑,要改的資料夾名);

GetFiles--獲取指定資料夾下的所有檔案路徑

string[] files = Directory.GetFiles(路徑);

GetDirectories--獲取指定資料夾下所有的資料夾路徑

string[] dirs = Directory.GetDirectories(path4);

檔案操作(File)

Exists--判斷某個檔案是否存在

File.Exists(路徑);

Delete--刪除檔案

該刪除方式在回收站是找不到的

Move

1.移動

File.Move(原始檔路徑,目標檔案路徑)

2.改名

File.Move(原始檔名,要改的檔名)

Copy--複製檔案

File.Copy(原始檔名,要賦值的檔名);

Create--建立檔案

File.Create(檔名)

檔案讀取

檔案讀取的步驟

1.判斷檔案是否存在:File.Exists()

2.開啟檔案,生成檔案流(FileStream)

//方法1
FileStream fs = File.Open(path, FileMode.Open);
//方法2
FileStream fs = new FileStream(path,FileMode.Open);

3.從FileStream流中讀取檔案內容

fs.Read(byte[], int, int)

第一引數:將流中讀取的內容儲存在該引數的位元組陣列中

第二引數:偏移,表示讀取的內容儲存位元組陣列中時,從第幾位開始存

第三引數:數量,表示當前位元組陣列從第偏移位開始,提供多少位元組供你儲存讀取內容

返回值:實際讀取的長度

4.關閉和釋放檔案流,表示關閉檔案

fs.Close();
fs.Dispose();

FileMode

CreateNew:建立一個新檔案,如果該檔案存在,則報錯

Create:建立一個新檔案,但是檔案存在,刪除舊檔案,建立新檔案,即:覆蓋原來的

Open:開啟一個已有的檔案

Appand:追加

注意:開啟檔案後必須關閉檔案,將操作檔案的程式碼放在try catch中保證出現錯誤也能關閉檔案

檔案寫入

步驟同文件讀取

1.檔案是否存在

2.建立或者開啟檔案

3.寫入檔案

4.關閉檔案釋放資源

using用法

1.引用名稱空間

using System.Collections;

2.規定一個變數的作用域,當using後的語句執行完畢時,自動釋放該變數佔用的資源

編碼格式

規定了字元文字在硬碟上與二進位制之間的規範

ASCII碼

擴充套件ASCII碼

GBK/GB2312/GB18303

UTF-8(萬國碼)

作用

將二進位制或位元組序列轉換成文字必須使用編碼格式對應一一轉換

將文字內容轉換為位元組序列也必須使用編碼格式進行一一轉換

亂碼

編碼與解碼的編碼格式不同可能導致亂碼

快速讀取和寫入文字檔案

快速讀取

File.ReadAllText

File.ReadAllLines

快速寫入

File.WriteAllText

File.WriteAllLines

本地檔案和巨集

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

public class LessonPath : MonoBehaviour
{
    public Text text;
    public InputField input;

    public Button write;
    public Button read;

    private string path = @"D:\桌面\新疆文字文件.txt";

    private void Awake()
    {
        //Debug.Log("dataPath: " + Application.dataPath);

        //text.text = "dataPath: " + Application.dataPath;
        //text.text += "\n\nstreamingAssetsPath: " + Application.streamingAssetsPath;
        //text.text += "\n\npersistentDataPath: " + Application.persistentDataPath;
        //要求在Windows平臺下,使用Application.streamingAssetsPath
        //在IOS和Android平臺下,使用Application.persistentDataPath
        //Windows下,可以使用Application.persistentDataPath

        //通過巨集來判斷當前的平臺
#if UNITY_STANDALONE_WIN //windows平臺
        text.text = "當前是Window平臺";
        path = Application.streamingAssetsPath + "/Info.txt";
#elif UNITY_IOS || UNITY_ANDROID //或者IOS或安卓平臺
        text.text = "當前是IOS或Android平臺";
        path = Application.persistentDataPath + "/Info.txt";
#endif

        write.onClick.AddListener(()=> {
            File.WriteAllText(path, input.text, Encoding.UTF8);
        });

        read.onClick.AddListener(() => {
            text.text = File.ReadAllText(path, Encoding.UTF8);
        });
    }

}

序列化與反序列化

序列化

將資料物件轉換成位元組序列的過程

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//二進位制流的形式序列化物件需要引入的名稱空間
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

public class LessonSerialize : MonoBehaviour
{
    public Student student;

    void Start ()
    {
        //s 就是資料物件, 記憶體中的物件
        Student s = new Student();
        s.name = "小明";
        s.age = 18;
        s.myClass = "Unity開發";
        //位元組序列 byte[]

        byte[] bytes = SerializeObject(s);
        Debug.Log(bytes.Length);

        File.WriteAllBytes(@"D:\桌面\Student.abab", bytes);

    }


    //序列化將資料物件轉成位元組陣列
    byte[] SerializeObject(object obj)
    {
        if (obj == null)
        {
            return null;
        }
        byte[] bytes = null;

        //1.建立記憶體流
        using (MemoryStream ms = new MemoryStream())
        {
            //2.建立一個二進位制格式
            BinaryFormatter bf = new BinaryFormatter();
            //3.將物件以二進位制的格式序列化到記憶體流中
            bf.Serialize(ms, obj);

            //4.從流中取出位元組陣列
            bytes = ms.GetBuffer();
        }
        return bytes;
    }
    
}

//修飾Student類,表示Stundent型別的物件是可以序列化的
[System.Serializable]
public class Student
{
    public string name;
    public int age;
    public string myClass;
}

反序列化

將位元組序列轉換成資料物件的過程

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public class LessonUnSerialize : MonoBehaviour
{

    void Start ()
    {
        byte[] bytes = File.ReadAllBytes(@"D:\桌面\Student.abab");
        //將位元組反序列化
        object obj = UnSerializeBytes(bytes);

        Student s = obj as Student;

        Debug.Log(s.name);
        Debug.Log(s.age);
        Debug.Log(s.myClass);

    }

    //將位元組陣列反序列化成資料物件
    object UnSerializeBytes(byte[] bytes)
    {
        if (bytes == null)
        {
            return null;
        }
        object obj = null;
        //1.建立記憶體流,並且將位元組陣列儲存到記憶體流中
        using (MemoryStream ms = new MemoryStream(bytes))
        {
            //2.建立一個二進位制格式
            BinaryFormatter bf = new BinaryFormatter();
            //3.通過二進位制格式從記憶體流中反序列化物件
            obj = bf.Deserialize(ms);
        }
        return obj;
    }
    
}