文件流FileStream

引入命名空间 System.IO

  1. 获取文件流
    File.Create(路径) 返回值 FileStream
    File.Open(路径,打开方式) 返回值 FileStream
    new FileStream(路径,打开方式,访问方式) 返回值 FileStream
  2. 文件流属性 方法
    Length 长度
    CanRead 文件流是否可读
    CanWrite 文件流是否克写
    Flush() 清除此流的缓冲区,使得所有缓冲数据都写入到文件中
    Close()关闭当前流并释放与之关联的所有资源
    Dispose()释放流对象使用的所有资源
    Write(字节数组,字节数组写入开始的索引,写入多少字节)
    Read(存放读取数据的字节数组,字节数组中存放数据开始的索引,读取多少字节) 返回值流索引前进多少位置
  3. 注意写入字符串的时候
    字符串转换为字节数组
    该数组长度转换为字节数组后写入 然后写入字符串字节数组
  4. 安全的使用文件流对象
    using(声明一个文件流对象)
    {//文件流操作 using语句块执行完 自动关闭文件流}
  5. 写入实例
//写入
FileStream stream = File.Open(Application.dataPath + "/Stream.stream", FileMode.Create, FileAccess.Write);
//写入 整型1024
byte[] bytes = BitConverter.GetBytes(1024);
stream.Write(bytes, 0, 4);
//写入字符串
string s = "写入字符串";  
byte[] b3 = Encoding.UTF8.GetBytes(s);
//写入字符串字节数组长度
byte[] b2 = BitConverter.GetBytes(b3.Length);      
stream.Write(b2, 0, 4);
//写入字符串 字节数组
stream.Write(b3, 0, b3.Length);
//关闭 
stream.Flush();
stream.Close();
stream.Dispose();
  1. 读取实例
//依次读取
FileStream stream2 = File.Open(Application.dataPath + "/Stream.stream", FileMode.Open, FileAccess.Read);
//读取1024
byte[] br1 = new byte[4];
int index = stream2.Read(br1, 0, 4);
print("移动" + index);
print(BitConverter.ToInt32(br1, 0));
//读取字符串字节数组长度
index = stream2.Read(br1, 0, 4);//字符串长度
print("移动" + index);
int sLength = BitConverter.ToInt32(br1, 0);
print(sLength);
//创建等长度的字节数组 存放字符串数据
byte[] br2 = new byte[sLength];
index = stream2.Read(br2, 0, sLength);
print("移动" + index);
print(Encoding.UTF8.GetString(br2));
//关闭
stream2.Flush();
stream2.Close();
stream2.Dispose();

//一次读取
using (FileStream s3 = File.Open(Application.dataPath + "/Stream.stream", FileMode.Open, FileAccess.Read))
{
    //总长度
    int totalLength = (int)s3.Length;
    byte[] by = new byte[totalLength];
    //读取所有
    s3.Read(by, 0, totalLength);
    //读取1024
    print(BitConverter.ToInt32(by, 0));
    //读取字符串字节数组长度
    int sLength = BitConverter.ToInt32(by, 4);
    print(sLength);
    //读取字符串
    print(Encoding.UTF8.GetString(by, 8, sLength));
    //下方可以注释
    s3.Flush();
    s3.Close();
    s3.Dispose();
}

你可能感兴趣的:(#,Unity数据持久化,c#)