第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 += "

streamingAssetsPath: " + Application.streamingAssetsPath;
        //text.text += "

persistentDataPath: " + 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;
    }
    
}
原文地址:https://www.cnblogs.com/yifengs/p/14299420.html