如何将文本文件的编码格式从Unicode更改为UTF-8

时间:2014-09-05 11:15:15

标签: macros vbscript

Dim txtFile, fileObj, streamObj, s

Set txtFile = CreateObject(fileName)

Set streamObj = CreatreObject("adodb.Stream")
streamObj.Charset = "UTF-8"
streamObj.open
Set fileObj = txtFile.OpenTextFile("filePath")

Do Until fileObj.AtEndOfStream
      s = fileObj.ReadLine
      txtObj.WriteText s
Loop

txtObj.SaveToFile "D:\A4\Message_tool\surya.msg", 2
fileObj.Close

执行此代码后,surya.msg的编码格式为" ANSCII"但我希望它是" UTF-8"

2 个答案:

答案 0 :(得分:2)

Const adTypeText = 2
Const adSaveCreateOverWrite = 2

Dim inputFile, outputFile
    inputFile = "input_file.txt"
    outputFile = "output_file.txt"

Dim inputStream
    Set inputStream  = WScript.CreateObject("adodb.stream")
    With inputStream
        .Type = adTypeText
        .Charset = "unicode"
        .Open
        .LoadFromFile inputFile
    End With

Dim outputStream
    Set outputStream = WScript.CreateObject("adodb.stream")
    With outputStream
        .Type = adTypeText
        .Charset = "utf-8"
        .Open
        .WriteText inputStream.ReadText
        .SaveToFile outputFile, adSaveCreateOverWrite
    End With

    inputStream.Close
    outputStream.Close

答案 1 :(得分:0)

可以使用OpenTextFile()类的FileSystemObject方法以常规方式打开Unicode编码的文本文件。只需将True / -1传递给第4个("格式")参数。

strText = objFSO.OpenTextFile(inputFile, , , True).ReadAll()

要将文字编码为UTF-8,您需要使用ADO Stream类。

Const adTypeText = 2
Const adSaveCreateOverWrite = 2

With CreateObject("ADODB.Stream")
    .Type = adTypeText
    .Charset = "utf-8"
    .Open
    .WriteText strText
    .SaveToFile "D:\A4\Message_tool\surya.msg", adSaveCreateOverWrite 
End With

有关Windows支持的字符编码列表,请查看以下注册表项:

HKEY_CLASSES_ROOT\MIME\Database\Charset