语言: vb.net 文件大小:1GB,等等。
文本文件的编码: UTF8(因此每个字符由不同的字节数表示)。
排序规则: UnicodeCI(当几个字符基本相同时,最流行的版本将是唯一的。)。我想我知道如何处理他的问题。
因为每个字符用不同的字节数表示,每行有不同的字符数,所以每行的字节数也不同。
我想我们必须为每一行计算哈希。我们还需要存储缓冲区位置所在的每一行。然后我们必须比较缓冲区。然后我们将检查是否显示同一行。
有没有最适合的特殊功能?
根据行的长度,您可以计算每行的 MD5 哈希值并将其存储在 a 中HashMap
:
Using sr As New StreamReader("myFile")
Dim lines As New HashSet(Of String)
Dim md5 As New Security.Cryptography.MD5Cng()
While sr.BaseStream.Position < sr.BaseStream.Length
Dim l As String = sr.ReadLine()
Dim hash As String = String.Join(String.Empty, md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(l)).Select(Function(x) x.ToString("x2")))
If lines.Contains(hash) Then
'Lines are not unique
Exit While
Else
lines.Add(hash)
End If
End While
End Using
未经测试,但这可能足以满足您的需求。我想不出更快的东西,仍然保持一些简洁的外表:)
这是当代答案
Public Sub makeUniqueForLargeFiles(ByVal strFileSource As String)
Using sr As New System.IO.StreamReader(strFileSource)
Dim changeFileName = reserveFileName(strFileSource, False, True)
Using sw As New System.IO.StreamWriter(reserveFileName(strFileSource, False, True), False, defaultEncoding)
sr.Peek()
Dim lines As New Generic.Dictionary(Of Integer, System.Collections.Generic.List(Of Long))
While sr.BaseStream.Position < sr.BaseStream.Length
Dim offset = sr.BaseStream.Position
Dim l As String = sr.ReadLine()
Dim nextOffset = sr.BaseStream.Position
Dim hash = l.GetHashCode
Do ' a trick to put the for each in a "nest" that we can exit from
If lines.ContainsKey(hash) Then
Using sr2 = New System.IO.StreamReader(strFileSource)
For Each offset1 In lines.Item(hash)
sr2.BaseStream.Position = offset1
Dim l2 = sr2.ReadLine
If l = l2 Then
Exit Do 'will sr2.dispose be called here?
End If
Next
End Using
Else
lines.Add(hash, New Generic.List(Of Long))
End If
lines.Item(hash).Add(offset)
sw.WriteLine(l)
Loop While False
sr.BaseStream.Position = nextOffset
End While
End Using
End Using
End Sub