using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
public class FileStreamStudy : MonoBehaviour
{
public string path = "C: \\Users\\FragrantPig\\Desktop\\FileStreamStudy.txt";
public Dictionary<int, string> dic = new Dictionary<int, string>();
// Start is called before the first frame update
void Start()
{
for(int i = 0; i < 10; i++)
{
dic[i] = i + "";
}
//文件写入
if (File.Exists(path))
{
File.Delete(path);
}
FileStream fsWriter = new FileStream(path, FileMode.Create);
foreach(var temp in dic)
{
string str = temp.ToString() + "\n";
byte[] data = Encoding.Default.GetBytes(str);
fsWriter.Write(data, 0, data.Length);
}
fsWriter.Flush();
fsWriter.Close();
//文件读
using (FileStream fsReader = new FileStream(path, FileMode.Open))
{
byte[] RData = new byte[1024];
while (true)
{
int r = fsReader.Read(RData, 0, RData.Length);
//如果读取到的字节数为0,说明已到达文件结尾,则退出while循
if (r == 0)
{
break;
}
string str = Encoding.Default.GetString(RData, 0, r);
Debug.Log(str);
}
}
}
}
示例:
其中,部分知识点:
using除了可以引用命名空间,还可以定义别名 和 自动释放对象。
…