问题描述
我有这段代码来读取大文件并使用 buffer 以字节为单位写入它们,我想读取特定大小。例如,我有一个大小为 100 kb 的文件。我只想读取最后 30kb 并将它们保存到一个新文件中。 我也不完全理解这个阅读器是如何工作的,但我想使用它所以它不能加载内存中的所有文件。
Sub readthis(filein As String,fileout As Of String,startingposition as integer)
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using inFile As New IO.FileStream(filein,FileMode.Open)
Using outFile As New IO.FileStream(fileout,FileMode.Append,FileAccess.Write)
Do
bytesRead = inFile.Read(buffer,buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer,bytesRead)
End If
Loop While bytesRead > 0
End Using
End Using
End Sub
解决方法
试试这个:
Private Sub Button1_Click(sender As Object,e As EventArgs) Handles Button1.Click
readthis("d:\log\tmp1.txt","d:\log\tmp2.txt",30)
End Sub
Sub readthis(filein As String,fileout As String,numlastbytes As Integer)
Dim fs As New IO.FileStream(filein,FileMode.Open,FileAccess.Read)
fs.Seek(-numlastbytes,SeekOrigin.End)
Dim bytearray(numlastbytes) As Byte
Dim numbytesread As Integer = fs.Read(bytearray,numlastbytes)
fs.Close()
My.Computer.FileSystem.WriteAllBytes(fileout,bytearray,False)
End Sub