文件流的读取:
//三个参数,第一个是路径,第二个是打开文件的方式,第三个是对文件数据的操作
FileStream fileread = new FileStream (@"C:\Users\CH\Desktop\111.txt" , FileMode . Open, FileAccess . Read);
byte [] bytes = new byte [1024 * 1024 ];//字节数组,通过字节数组限制每次读取多少数据
int r = fileread .Read(bytes, 0 , bytes. Length);//参数:字节数组,从0位置开始读,每次读bytes.Length长度
string str = Encoding. Default .GetString(bytes, 0 , r);//转换编码为字符串
fileread . Close();//删除流
fileread . Dispose();//释放流
Console .WriteLine(str);
Console .ReadKey();
文件的写入:
可以用using来省去Close();Dispose();这两个方法的调用;
using(FileStream filew = new FileStream (@"新建文本文档.txt" , FileMode. OpenOrCreate, FileAccess . Write))
{
string str = "天是晴朗的天" ;
byte [] buffer = Encoding. Default .GetBytes(str);
filew . Write(buffer, 0 , buffer .Length);
filew . Close();
filew . Dispose();
Console .WriteLine( "OK" );
Console .ReadKey();
}
StreamReader与StreamWrite:针对字符串的读写
using ( StreamReader rd = new StreamReader ( @"C:\Users\CH\Desktop\111.txt" ,Encoding . Default))
while (!rd.EndOfStream)
{
Console.WriteLine(rd.ReadLine());
}
Console .ReadKey();
网友评论