
imports System.IOimports Microsoft.VisualBasic.fileIOModule 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 SubEnd 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 )); 总结 以上是内存溢出为你收集整理的在vb.net中读取非常大的文本文件时出现内存不足错误全部内容,希望文章能够帮你解决在vb.net中读取非常大的文本文件时出现内存不足错误所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)