小弟用“记事本”编缉了一段文字,然后存成UTF-8的格式
然后在通过程序显示出来,程序代码如下:'显示文件内容
Private Sub ShowContent(ByVal sFileName As String)
On Error GoTo ShowErr:
Dim objTextStream As TextStream
Dim objFile As New FileSystemObject
Set objTextStream = objFile.OpenTextFile(sFileName)
Dim sStr As String
Dim UTFBytes() As Byte
Dim sFileContent As String
With objTextStream
Do While Not .AtEndOfStream
sStr = .ReadLine
UTFBytes = StrConv(sStr, vbFromUnicode)
sFileContent = sFileContent & UTF8_Decode(UTFBytes) & vbCrLf
Loop
End With
rtbFileContent.Text = sFileContent 'rtbFileContent为RichTextBox控
'件
Exit Sub
ShowErr:
Debug.Print Err.Description
End Sub'下面是对UTF8的解码
Public Function UTF8_Decode(UTF8Bytes() As Byte) As String
On Error GoTo DecodeErr:
Dim llen As Long
Dim lLBound As Integer
Dim lUBound As Integer
lLBound = LBound(UTF8Bytes)
lUBound = UBound(UTF8Bytes)
llen = lUBound - lLBound + 1
Dim lBufferSize As Long
lBufferSize = llen * 2
Dim sBuffer As String
sBuffer = String$(lBufferSize, Chr(0))
Dim lRet As Long '
lRet = MultiByteToWideChar(CP_UTF8, 0, VarPtr(Bytes(0)), llen, StrPtr(sBuffer), lBufferSize)
If lRet <> 0 Then
UTF8_Decode = Left(sBuffer, lRet)
End If
Exit Function
DecodeErr:
Debug.Print Err.Description
End Function问题:(1)当汉字的个数是偶数个时,结果就会出现乱码(奇数就能得到正确的值)
我看了一下主要是sStr = .ReadLine没有得到正确的值(如果汉字个数
是偶数个时,sStr的最后就有个?)结果转换后最后一个字符就是个? (2)我试过用二进制方式读出每个字节然后再转则不会有错 (3)可是我就是想用.ReadLine存成字符串后再转请高手们帮帮忙呀,
十分感谢呀!!!!
然后在通过程序显示出来,程序代码如下:'显示文件内容
Private Sub ShowContent(ByVal sFileName As String)
On Error GoTo ShowErr:
Dim objTextStream As TextStream
Dim objFile As New FileSystemObject
Set objTextStream = objFile.OpenTextFile(sFileName)
Dim sStr As String
Dim UTFBytes() As Byte
Dim sFileContent As String
With objTextStream
Do While Not .AtEndOfStream
sStr = .ReadLine
UTFBytes = StrConv(sStr, vbFromUnicode)
sFileContent = sFileContent & UTF8_Decode(UTFBytes) & vbCrLf
Loop
End With
rtbFileContent.Text = sFileContent 'rtbFileContent为RichTextBox控
'件
Exit Sub
ShowErr:
Debug.Print Err.Description
End Sub'下面是对UTF8的解码
Public Function UTF8_Decode(UTF8Bytes() As Byte) As String
On Error GoTo DecodeErr:
Dim llen As Long
Dim lLBound As Integer
Dim lUBound As Integer
lLBound = LBound(UTF8Bytes)
lUBound = UBound(UTF8Bytes)
llen = lUBound - lLBound + 1
Dim lBufferSize As Long
lBufferSize = llen * 2
Dim sBuffer As String
sBuffer = String$(lBufferSize, Chr(0))
Dim lRet As Long '
lRet = MultiByteToWideChar(CP_UTF8, 0, VarPtr(Bytes(0)), llen, StrPtr(sBuffer), lBufferSize)
If lRet <> 0 Then
UTF8_Decode = Left(sBuffer, lRet)
End If
Exit Function
DecodeErr:
Debug.Print Err.Description
End Function问题:(1)当汉字的个数是偶数个时,结果就会出现乱码(奇数就能得到正确的值)
我看了一下主要是sStr = .ReadLine没有得到正确的值(如果汉字个数
是偶数个时,sStr的最后就有个?)结果转换后最后一个字符就是个? (2)我试过用二进制方式读出每个字节然后再转则不会有错 (3)可是我就是想用.ReadLine存成字符串后再转请高手们帮帮忙呀,
十分感谢呀!!!!
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货