using System.IO;
using UnityEngine;
public class BRTest : MonoBehaviour
{
[ContextMenu("写入")]
public void Write()
{
string path = Application.dataPath + "/test.bytes";
FileStream fs = new FileStream(path, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write("你好");
bw.Write(10000);
bw.Write(5);
for (int i = 0; i < 5; i++)
{
bw.Write(i);
if (i == 4)
{
bw.Write(999999);
}
else
{
bw.Write(i * 100);
}
}
bw.Write("哈哈哈");
bw.Write(123321);
bw.Flush();
bw.Close();
bw.Dispose();
fs.Close();
fs.Dispose();
Debug.Log("finish");
}
[ContextMenu("读取")]
public void Read()
{
string path = Application.dataPath + "/test.bytes";
FileStream fs = new FileStream(path, FileMode.Open);
BinaryReader br = new BinaryReader(fs);
var a = br.ReadString();
var b = br.ReadInt32();
var count = br.ReadInt32();
for (int i = 0; i < count; i++)
{
var aa = br.ReadInt32();
var bb = br.ReadInt32();
int cc = 0;
}
var d = br.ReadString();
var e = br.ReadInt32();
Debug.Log("finish");
}
}
写入到内存中的byte[]然后读取出来
[ContextMenu("二进制写入内存和内存读取")]
public void WriteOrRead()
{
// 写入内存流二进制
MemoryStream s = new MemoryStream();
BinaryWriter bw = new BinaryWriter(s);
bw.Write(1000);
bw.Write("测试....");
bw.Write(48699);
byte[] bytes = s.ToArray();
s.Flush();
s.Dispose();
s.Close();
bw.Dispose();
bw.Close();
// 读取内存流二进制
MemoryStream ms = new MemoryStream(bytes);
BinaryReader br = new BinaryReader(ms);
int a = br.ReadInt32();
string b = br.ReadString();
int c = br.ReadInt32();
ms.Flush();
ms.Dispose();
ms.Close();
br.Dispose();
br.Close();
}