gpt4 book ai didi

.net - 在 vb.net 中读取非常大的文本文件时出现内存不足错误

转载 作者:行者123 更新时间:2023-12-03 03:22:27 25 4
gpt4 key购买 nike

我的任务是处理 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

这是一个非常简单的程序,一次读取一行文本文件,所以我认为它不应该在缓冲区中占用太多内存。

对于我的一生,我无法弄清楚为什么它会崩溃。这里有人有什么想法吗?

最佳答案

我不知道这是否能解决您的问题,但不要使用 peek,请将循环更改为:(这是 C#,但您应该能够将其转换为 VB)

while (_read.ReadLine() != null)
{
count += 1
}

如果您需要在循环内使用文本行而不是仅计算行数,只需将代码修改为

while ((lineoftext = _read.ReadLine()) != null)
{
count += 1
//Do something with lineoftext
}
<小时/>

有点题外话,有点作弊,如果每一行确实有 1563 个字符长(包括行结尾)并且文件是纯 ASCII(因此所有字符占用一个字节),您可以这样做(再次是 C# 但你应该能够翻译)

long bytesPerLine = 1563;
string inputfile = @"C:\Split\BIGFILE.txt"; //The @ symbol is so we don't have to escape the `\`
long length;

using(FileStream stream = File.Open(inputFile, FileMode.Open)) //This is the C# equivilant of the try/finally to close the stream when done.
{
length = stream.Length;
}

Console.WriteLine("Total Lines in {0}: {1}", inputfile, (length / bytesPerLine ));

关于.net - 在 vb.net 中读取非常大的文本文件时出现内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14699039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com