[英]Reading multiple files in a Stream
嘿!
如何一次讀取多個文本文件? 我想要做的是讀取一系列文件,並將它們全部附加到一個大文件中。 我現在正在這樣做:
不幸的是,我觀察到平均讀取速度僅為4MB /秒。 我注意到,當我在磁盤上移動文件時,速度達到40 MB /秒。 我正在考慮將文件緩存在Stream中,並像進行寫入一樣一次讀取所有文件。 知道我該如何實現嗎?
更新:
foreach (string file in System.IO.Directory.GetFiles(InputPath))
{
using (StreamReader sr = new StreamReader(file))
{
try
{
txt = txt+(file + "|" + sr.ReadToEnd());
}
catch // out of memory exception
{
WriteString(outputPath + "\\" + textBox3.Text, ref txt);
//sb = new StringBuilder(file + "|" + sr.ReadToEnd());
txt = file + "|" + sr.ReadToEnd();
}
}
Application.DoEvents();
}
這就是我現在的做法。
一方面,您需要區分流 (二進制數據)和StreamReader
或更一般的TextReader
(文本數據)。
聽起來您想創建一個TextReader
的子類,該子類將(在其構造函數中)接受一堆TextReader
參數。 您無需在這里急切地閱讀任何內容 ……但是在您覆蓋的Read
方法中,您應該從“當前”閱讀器進行閱讀,直到用盡為止,然后從下一個開始。 請記住, Read
沒有填補它被賦予了緩沖區-所以你可以喜歡做一些事情:
while (true)
{
int charsRead = currentReader.Read(buffer, index, size);
if (charsRead != 0)
{
return charsRead;
}
// Adjust this based on how you store the readers...
if (readerQueue.Count == 0)
{
return 0;
}
currentReader = readerQueue.Dequeue();
}
我強烈懷疑已經有第三方庫可以進行這種脫膠,請注意...
如果您要做的只是讀取文件,然后將它們串聯在一起成為磁盤上的新文件,則可能根本不需要編寫代碼。 使用Windows復制命令:
C:\> copy a.txt+b.txt+c.txt+d.txt output.txt
您可以根據需要通過Process.Start
進行調用。
當然,這假定您沒有對文件或其內容執行任何自定義邏輯。
這應該很快(但是它將整個文件加載到內存中,因此可能無法滿足所有需求):
string[] files = { @"c:\a.txt", @"c:\b.txt", @"c:\c.txt" };
FileStream outputFile = new FileStream(@"C:\d.txt", FileMode.Create);
using (BinaryWriter ws = new BinaryWriter(outputFile))
{
foreach (string file in files)
{
ws.Write(System.IO.File.ReadAllBytes(file));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.