【发布时间】:2013-02-05 17:35:13
【问题描述】:
我的任务是处理一个 3.2GB 的定宽分隔文本文件。每行有 1563 个字符长,文本文件中大约有 210 万行。在阅读了大约 100 万行之后,我的程序因内存不足异常错误而崩溃。
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Module TestFileCount
''' <summary>
''' Gets the total number of lines in a text file by reading a line at a time
''' </summary>
''' <remarks>Crashes when count reaches 1018890</remarks>
Sub Main()
Dim inputfile As String = "C:\Split\BIGFILE.txt"
Dim count As Int32 = 0
Dim lineoftext As String = ""
If File.Exists(inputfile) Then
Dim _read As New StreamReader(inputfile)
Try
While (_read.Peek <> -1)
lineoftext = _read.ReadLine()
count += 1
End While
Console.WriteLine("Total Lines in " & inputfile & ": " & count)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
_read.Close()
End Try
End If
End Sub
End Module
这是一个非常简单的程序,一次读取一行文本文件,所以我认为它不应该在缓冲区中占用太多内存。
对于我的生活,我无法弄清楚它为什么会崩溃。这里有人有什么想法吗?
【问题讨论】:
-
这可能是您的
StreamReader的缓冲区大小吗?您可以在构造函数中更改大小。 -
另外,你是为 x86 还是 x64 编译这个?
-
每次都会在完全相同的文件偏移处崩溃吗?如果是这样,请确认预期的换行符确实存在于该位置。
-
你确定换行符是
\n\r吗?在换行方面,您的文本编辑器可能比StreamReader更宽容。 -
为什么要读整行?只需获取每行的第一个字符并添加到您的计数中...?
标签: .net vb.net out-of-memory