7605
社区成员
'读
Dim oStream As ADODB.Stream
Dim sText As String
Set oStream = New ADODB.Stream
oStream.Open
oStream.Charset = "Unicode"
oStream.Type = adTypeText
oStream.LoadFromFile FileName
sText = oStream.ReadText()
oStream.Close
'写
Dim oStream As ADODB.Stream
Dim sText As String
Set oStream = New ADODB.Stream
oStream.Open
oStream.Charset = "Ascii"
oStream.Type = adTypeText
oStream.WriteText sText
oStream.SaveToFile FileName, adSaveCreateOverWrite
oStream.Close
Private Declare Function MultiByteToWideChar Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByRef lpMultiByteStr As Any, ByVal cchMultiByte As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long) As Long
Private Declare Function WideCharToMultiByte Lib "kernel32" (ByVal CodePage As Long, ByVal dwFlags As Long, ByVal lpWideCharStr As Long, ByVal cchWideChar As Long, ByRef lpMultiByteStr As Any, ByVal cchMultiByte As Long, ByVal lpDefaultChar As Long, ByVal lpUsedDefaultChar As Long) As Long
'常用的代码页:
const cpUTF8 =65001
const cpGB2312 = 936
const cpGB18030=54936
const cpUTF7 =65000
Function MultiByteToUTF16(UTF8() As Byte, CodePage As Long) As String
Dim bufSize As Long
bufSize = MultiByteToWideChar(CodePage, 0&, UTF8(0), UBound(UTF8) + 1, 0, 0)
MultiByteToUTF16 = Space(bufSize)
MultiByteToWideChar CodePage, 0&, UTF8(0), UBound(UTF8) + 1, StrPtr(MultiByteToUTF16), bufSize
End Function
Function UTF16ToMultiByte(UTF16 As String, CodePage As Long) As Byte()
Dim bufSize As Long
Dim arr() As Byte
bufSize = WideCharToMultiByte(CodePage, 0&, StrPtr(UTF16), Len(UTF16), 0, 0, 0, 0)
ReDim arr(bufSize - 1)
WideCharToMultiByte CodePage, 0&, StrPtr(UTF16), Len(UTF16), arr(0), bufSize, 0, 0
UTF16ToMultiByte = arr
End Function
Private Sub Command1_Click()
MsgBox MultiByteToUTF16(UTF16ToMultiByte("ab中,c", cpUTF8), cpUTF8)
End Sub
Private Sub Form_Load()
Text2.Text = "3841195078-87113-iMANHpBAcI"
End Sub
Private Sub cmdRead_Click() '读Unicode文本
Dim textBytes() As Byte, headBytes(2) As Byte
fn = App.Path & "\MyUnicode.txt"
If Dir(fn) = "" Then
MsgBox "文件不存在,请先单击【写入】按钮生成“MyUnicode.txt”文件。", vbInformation
Exit Sub
End If
Open fn For Binary As #1
Get #1, , headBytes() '读取文件头。
Close #1
If headBytes(0) = 255 And headBytes(1) = 254 Then '是Unicode编码。十六进制为:FF 、FE。
Open fn For Binary As #1
ReDim textBytes(LOF(1) - 2) '减去文件头占用的2个字节。
Get #1, 3, textBytes() '第三个字节起为文本内容。
Close #1
Text1.Text = textBytes() '在 VB 中字符串是 UniCode 格式,所以Unicode码直接赋值即可显示文本内容。
Else
MsgBox "非Unicode编码,不予读入,请单击【写入】按钮。", vbInformation
End If
End Sub
Private Sub cmdWrite_Click() '写Unicode文本。
Dim textBytes() As Byte, headBytes(2) As Byte
headBytes(0) = 255: headBytes(1) = 254
textBytes() = Text2.Text
Open App.Path & "\MyUnicode.txt" For Binary As #1
Put #1, 1, headBytes() ' 写文件头。
Put #1, 3, textBytes() ' 写文本内容。
Close #1
End Sub