C#大文件讀取寫入

接上一篇文章,繼續(xù)大文件的問題

1.這次我還是創(chuàng)建控制臺程序,按自己需求自定義數(shù)組的大小讀取

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)
        {    
            using (Stream fs = new FileStream(@"C: \Users\xg\Desktop\計劃表.txt", FileMode.Open))
            {
                string path = @"C: \Users\xg\Desktop\bb.txt";
                byte[] bytes = new byte[1024 * 1024];
                int len;
                while ((len = fs.Read(bytes, 0, bytes.Length)) > 0)
                {
                    string s = Encoding.GetEncoding("utf-8").GetString(bytes, 0, len);
                    Console.Write(s);
                    MyStreamWriter(path, s);
                }
            }
        //使用StreamWrite  StreamReader 不需要考慮文件的編碼問題
        /// <summary>
        /// 寫文件
        /// </summary>
        /// <param name="path">文件路徑</param>
        /// <param name="Content">讀取的字符串</param>
        static void MyStreamWriter(string path, string Content)
        {
            using (Stream inStream = new FileStream(path, FileMode.Create))
            using (StreamWriter write = new StreamWriter(inStream))
            {
                write.WriteLine(Content);
            }
        }
     }
}


2.創(chuàng)建一個控制程序,逐行讀取大文件,寫入目標文件

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 ss = @"C:\Users\xg\Desktop\計劃表.txt";
            MyStreamReader2(ss);
 static void MyStreamReader2(string path)
        {
            string file = @"C: \Users\xg\Desktop\cb.txt";
            StringBuilder sb = new StringBuilder();
            using (Stream outStream = new FileStream(path, FileMode.Open))//打開文件流
            using (StreamReader reader = new StreamReader(outStream, Encoding.GetEncoding("utf-8")))//讀文件流
            {
                while (reader.Peek() > -1)//讀下一個字符返貨是否字符個數(shù)為0 
                {
                    sb = sb.AppendLine(reader.ReadLine());//讀取一行
                   using (Stream inStream = new FileStream(file, FileMode.Create))
                    using (StreamWriter write = new StreamWriter(inStream))
                    {
                        write.WriteLine(sb);
                    }
                }
            }

         }
       }
   }

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容