C#的FileStream类提供了最原始的字节级上的文件读写功能,但我们习惯于对字符串操作,于是StreamWriter和 StreamReader类增强了FileStream,它让我们在字符串级别上操作文件,但有的时候我们还是需要在字节级上操作文件,却又不是一个字节 一个字节的操作,通常是2个、4个或8个字节这样操作,这便有了BinaryWriter和BinaryReader类,它们可以将一个字符或数字按指定 个数字节写入,也可以一次读取指定个数字节转为字符或数字。
1.BinaryWriter类
BinaryWriter类以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。
常用的方法:
Close 关闭当前的BinaryWriter和基础流
Seek 设置当前流中的位置
Write 将值写入当前流
2.BinartReader类
BinartReader类用特定的编码将基元数据类型读作二进制值。
常用的方法:
Close 关闭当前阅读器及基础流
Read 从基础流中读取字符,并提升流的当前位置
ReadBytes 从当前流将count个字节读入字节数组,并使当前位置提升count个字节
ReadInt32 从当前流中读取4个字节有符号整数,并使流的当前位置提升4个字节
ReadString 从当前流读取一个字符串。字符串有长度前缀,一次7位地被编码为整数
下面看一个实例:
BinaryWriter 和 BinaryReader 类用于读取和写入数据,而不是字符串。
using UnityEngine;
using System;
using System.Text;
using System.IO;
using System.Collections;
using System.Collections.Generic;
public class FileOperator : MonoBehaviour {
// Use this for initialization
void Start () {
WriteFile ();
ReadFile();
}
void ReadFile() // 读取文件
{
FileStream fs = new FileStream ("D:\\MemoryStreamTest.txt", FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader (fs);
//以二进制方式读取文件中的内容
int i = r.ReadInt32 ();
float f = r.ReadSingle ();
double d = r.ReadDouble ();
bool b = r.ReadBoolean ();
string s = r.ReadString();
Debug.Log (i);
Debug.Log (f);
Debug.Log (d);
Debug.Log (b);
Debug.Log (s);
r.Close ();
fs.Close ();
}
void WriteFile() // 写入文件
{
FileStream fs = new FileStream ("D:\\BinaryStreamTest.txt", FileMode.OpenOrCreate);
BinaryWriter w = new BinaryWriter (fs);
//以二进制方式向创建的文件中写入内容
w.Write (666); // 整型
w.Write (66.6f); // 浮点型
w.Write (6.66); // double型
w.Write(true); // 布尔型
w.Write ("六六六"); // 字符串型
w.Close ();
fs.Close();
}
}