[英]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.