我需要读取一个大的文本文件,并在每一行中搜索一个字符串,每一行以换行符分隔,我需要尽量减少I/O和RAM的使用。
我的想法是将文件拆成块,所以我有两种方法:
1)使用类似以下的方法分割FileStream,但这样做会冒着把文本行分割成两半的风险,这可能会使事情变得复杂:
using (FileStream fsSource = new FileStream("InputFiles\\1.txt", FileMode.Open, FileAccess.Read))
{
// Read the source file into a byte array.
int numBytesToRead = 1024; // Your amount to read at a time
byte[] bytes = new byte[numBytesToRead];
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
//done something with the lines here.
}
}
2) 创建一个扩展方法,将行列表拆分为更小的行列表,然后在每行中搜索单词,但我不确定这种方法如何影响I/O和RAM!
public static IEnumerable<IEnumerable<TValue>> Chunk<TValue>(this IEnumerable<TValue> values, int chunkSize)
{
using (var enumerator = values.GetEnumerator())
{
while (enumerator.MoveNext())
{
yield return GetChunk(enumerator, chunkSize).ToList();
}
}
}
private static IEnumerable<T> GetChunk<T>(IEnumerator<T> enumerator, int chunkSize)
{
do
{
yield return enumerator.Current;
} while (--chunkSize > 0 && enumerator.MoveNext());
}
有没有其他想法或方法可以使用?
提前致谢。