简单的读写文件,文件内容比较少可以使用下面这种方法,但是注意,这种方法只能创建文件,不能创建文件夹,所以需要创建好目录,这种WriteAllText写入方式每次都会覆盖掉先前的内容,追加字符串就可以使用AppendAllText方法
Environment.NewLine这个方法是个换行符
void Start () {
string path = @"D:\Unity_Program\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
print(readText);
}
按照流读取文件(常用方式),这种方式同样不能创建路径
// Use this for initialization
void Start () {
Load();
}
//写入文件内容
public void Save()
{
StringBuilder sb = new StringBuilder();//声明一个可变字符串
for (int i = 0; i < 10; i++)
{
//循环给字符串拼接字符
sb.Append(i).Append("[]");
}
//写文件 文件名为save.text
//这里的FileMode.create是创建这个文件,如果文件名存在则覆盖重新创建
FileStream fs = new FileStream(@"D:/Unity_Program" + "/save.txt", FileMode.Create);
//存储时时二进制,所以这里需要把我们的字符串转成二进制
byte[] bytes = new UTF8Encoding().GetBytes(sb.ToString());
fs.Write(bytes, 0, bytes.Length);
//每次读取文件后都要记得关闭文件
fs.Close();
print("写入完成");
}
//读取
public void Load()
{
//FileMode.Open打开路径下的save.text文件
FileStream fs = new FileStream(@"D:/Unity_Program"+ "/save.txt", FileMode.Open);
byte[] bytes = new byte[1024];
int count = (int)fs.Length;
fs.Read(bytes, 0, count);
//将读取到的二进制转换成字符串
string s = new UTF8Encoding().GetString(bytes);
Debug.Log(s);
fs.Close();
}