查看文件属性
void Get()
{
FileInfo f = new FileInfo(Application.dataPath + "/Filed/b.txt");//获取路径,拿到文件
//print(f.Name);//文件名
//print(f.Length);//文件长度
//print(f.FullName);//文件全名
//print(f.Exists);//是否存在
//print(f.DirectoryName);//文件所在位置
//print(f.IsReadOnly);//是否只读
//if (!f.Exists)
//{
// f.Create();//如果不存在,创建一个新文件
//}
//f.MoveTo(Application.dataPath + "/Filed/c.txt");//文件重命名
}
文件写入
void WriteFile()
{
string path = Application.dataPath + "/Filed/c.txt";//获得文件路径
string s1 = "hello word";
File.WriteAllText(path, s1);//文本写入
string[] s2 = { "小普", "海涛", "小廖" };
File.WriteAllLines(path, s2);//字符串写入
string s3 = "正勇";
byte[] s4 = Encoding.UTF8.GetBytes(s3);//转码
File.WriteAllBytes(path, s4);//字节写入
File.AppendAllText(path, "\n小普");//追加
}
读取文件
void ReadFile()
{
string path = Application.dataPath + "/Filed/a.txt";
string s1 = File.ReadAllText(path);//读取字符
print(s1);
string[] s2 = File.ReadAllLines(path);//读取字符串
foreach (var item in s2)
{
print(s2);//编历
}
byte[] s3 = File.ReadAllBytes(Application.dataPath + "/Filed/bg.png");
string s4 = Encoding.UTF8.GetString(s3);//读取图片
print(s4);
}
文件读写
void WriteStreamFile()
{
string path = Application.dataPath + "/Filed/b.txt";
if (File.Exists(path))//是否存在
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))//创建 FileStream 类的实例
{
string s1 = "hello word";
byte[] s2 = Encoding.UTF8.GetBytes(s1);//转码写入
fs.Write(s2, 0, s2.Length);//转码写入
fs.Flush();//刷新缓存区
fs.Close();
}
}
}
void ReadStreamFile()
{
string path = Application.dataPath + "/Filed/a.txt";
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))//创建 FileStream 类的实例
{
byte[] s1 = new byte[fs.Length];//定义存放文件信息的字节数组
int lenth = fs.Read(s1, 0, s1.Length);//读取文件信息
string s2= Encoding.UTF8.GetString(s1);//输出文件信息
print(s2);
fs.Close();
}
}
- 通过 StreamReader读 StreamWriter写文件
public void Sign()
{
string path = Application.dataPath + "/Filed/user.txt";
if (File.Exists(path))
{
using(StreamReader reader=new StreamReader(path, Encoding.UTF8))//实例化reader对象
{
while (true)
{
string str = reader.ReadLine();//从第一行开始读取
if (str==null)
{
break;
}//读到结尾
}
reader.Close();
}
}
using (StreamWriter writer=new StreamWriter("Application.dataPath +"/File/user.txt"))
{
writer.WriteLine(new char[]{'2','3'});//写入
writer.Close();
}