[英]Out of memory exception reading and writing text file
执行以下代码几秒钟后,我收到内存不足异常。 在抛出异常之前它不会写任何东西。 文本文件的大小约为 0.5 GB。 我正在编写的文本文件最终将占用大约 3/4 GB 的空间。 有什么技巧可以绕过这个异常吗? 我认为这是因为文本文件太大。
public static void ToCSV(string fileWRITE, string fileREAD)
{
StreamWriter commas = new StreamWriter(fileWRITE);
var readfile = File.ReadAllLines(fileREAD);
foreach (string y in readfile)
{
string q = (y.Substring(0,15)+","+y.Substring(15,1)+","+y.Substring(16,6)+","+y.Substring(22,6)+ ",NULL,NULL,NULL,NULL");
commas.WriteLine(q);
}
commas.Close();
}
我已将代码更改为以下代码,但仍然得到相同的异常?
public static void ToCSV(string fileWRITE, string fileREAD)
{
StreamWriter commas = new StreamWriter(fileWRITE);
using (FileStream fs = File.Open(fileREAD, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
string y;
while ((y = sr.ReadLine()) != null)
{
string q = (y.Substring(0, 15) + "," + y.Substring(15, 1) + "," + y.Substring(16, 6) + "," + y.Substring(22, 6) + ",NULL,NULL,NULL,NULL");
commas.WriteLine(q);
}
}
commas.Close();
}
在下面的文章中,您可以找到多种读取和写入大文件的方法。 在 C# 中使用流读取大型文本文件
基本上,您只需要读取将被重用的缓冲区中的字节。 这样您就可以将非常少量的文件加载到内存中。
不要读取整个文件,而是尝试逐行读取和处理。 这样您就不会冒遇到内存不足异常的风险。 因为即使您成功地为程序组织了更多内存,总有一天文件会再次变得太大。
但是如果您使用较少的内存,程序可能会降低速度,因此基本上您必须平衡内存使用和执行时间。 一种解决方法是使用缓冲输出,一次读取多于一行或在多个线程中转换字符串。
逐行阅读文件,它将帮助您避免OutOfMemoryException
。 我个人更喜欢使用using
来处理流。 它确保在出现异常时关闭文件。
public static void ToCSV(string fileWRITE, string fileREAD)
{
using(var commas = new StreamWriter(fileWRITE))
using(var file = new StreamReader("yourFile.txt"))
{
var line = file.ReadLine();
while( line != null )
{
string q = (y.Substring(0,15)+","+y.Substring(15,1)+","+y.Substring(16,6)+","+y.Substring(22,6)+ ",NULL,NULL,NULL,NULL");
commas.WriteLine(q);
line = file.ReadLine();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.