拷贝文件有两种方式:
1.将源文件内容全部读到内存中,再写到目标文件中:File.ReadAllText、File.WriteAllText
2.如果文件非常大会占内存、慢。需要读一行处理一行的机制,这就是流(Stream)。Stream会只读取要求的位置、长度的内容。不会将所有内容一次性读取到内存中,有一个指针,指针指到哪里才能读、写到哪里。
流有很多种类,文件流是其中一种。下面的FileStream就是其一
(1)FileStream 文件流的几种创建方式:
namespace 文件流的几种创建方式 { class Program { static void Main(string[] args) { FileStream fs = new FileStream();//第1种,指定参数即可 FileStream fs1 = File.OpenRead("1.txt"); //第二种,只读模式 FileStream fs2 = File.OpenWrite("1.txt");//第3种读写文件流 } } }
(2)FileStream文件流进行文件拷贝
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace 通过文件流进行文件拷贝 { class Program { static void Main(string[] args) { string source = @"c:\中国.txt"; string target = @"e:\中国.txt"; CopeFile(source, target); Console.WriteLine("d"); Console.ReadKey(); } //文件拷贝流 private static void CopeFile(string source, string target) { //1.创建一个读取源文件的文件流 using (FileStream fsread = new FileStream(source, FileMode.Open, FileAccess.Read)) { long len = fsread.Length;//获取读取的文件的大小 //2.创建一个写入新文件的文件流 using (FileStream fswrite = new FileStream(target, FileMode.Create, FileAccess.Write)) { //创建缓冲区 byte[] buffer = new byte[1024 * 1024 * 5]; //指定缓存大小,每次5M,不直接写数字,更方便阅读 int bytecount = fsread.Read(buffer,0,buffer.Length); while (bytecount > 0)//判断读取的字节是否存在 { //把刚刚读取到的内容写入到新文件流中 fswrite.Write(buffer, 0, bytecount); //需要循环执行读写操作 //把上次读取到内容写入完毕后,继续再读取 bytecount = fsread.Read(buffer, 0, buffer.Length); //会自动定位其读取的位置 double d = fsread.Position * 1.0 / len; Console.WriteLine(d); Console.ReadKey(); //结束 //Console.WriteLine("ok"); } } } } #region IDisposable接口 class Person:IDisposable { public void Dispose() { //throw new NotImplementedException(); Console.WriteLine("ok"); } #endregion } } }
2.StreamReader
如果对文本文件需要读取一部分显示一部分,则使用FileStream会有问题,因为FileStream可能会在读取的时候把一个汉字的字节数给分开。所以造成显示的时候无法正确显示字符串。
所以对于读取大文本文件一般使用StreamReader类,对于大文本文件写入一般用StreamWriter类。
StreamWriter类
using (StreamWriter sw=new StreamWriter("1.txt",false,Encoding.UTF8)) { //执行循环写入 for (int i = 0; i < 100; i++) { sw.WriteLine(i+"======"+System.DateTime.Today.ToString()); } } Console.WriteLine("ok"); Console.ReadKey();
StreamReader类
using (StreamReader sr = new StreamReader("中国城市.txt", Encoding.Default)) { int count = 0; while ( sr.ReadLine() != null) { count++; Console.WriteLine( sr.ReadLine()); } Console.WriteLine(count ); }
说点什么
欢迎讨论