我有一个大小为 50GB 及以上的 Json 文件。
以下是我编写的用于读取一小部分 Json 的内容。我现在需要修改它以读取大文件。
internal static IEnumerable<T> ReadJson<T>(string filePath)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (StreamReader sr = new StreamReader(filePath))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(line);
XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(jsonBytes, XmlDictionaryReaderQuotas.Max);
var myPerson = ser.ReadObject(jsonReader);
jsonReader.Close();
yield return (T)myPerson;
}
}
}
- 如果我在当前代码中构造 StreamReader 时指定缓冲区大小就足够了吗?
- 如果我在这里错了,请纠正我。缓冲区大小基本上指定一次从磁盘读取到内存的数据量。因此,如果文件大小为 100MB,缓冲区大小为 5MB,则每次读取 5MB 到内存,直到读取整个文件。
- 假设我对第 3 点的理解是正确的,对于如此大的文本文件,理想的缓冲区大小是多少? int.Max 大小是一个坏主意吗?在 64 位 PC 中,int.Max 大小为 2147483647。我假设缓冲区大小以字节为单位,计算结果约为 2GB。这本身可能会消耗时间。我正在寻找 100MB - 300MB 之类的缓冲区大小。
它将一次读取一行(输入文件的),可能是 10 个字节,也可能是 50GB。所以归结为:输入文件的结构如何?如果输入 JSON 有换行符other而不是在物体之间的间隙处干净地清洁,这可能会变得非常糟糕。
缓冲区大小可能会影响读取量在寻找时对于每行的末尾,但最终:它每次都需要找到一个换行符(至少,目前是如何编写的)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)