how to change the encoding format of text file fro

2019-07-13 10:36发布

问题:

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

After the execution this code the encoding format of surya.msg is "ANSCII" but I want it to be "UTF-8"

回答1:

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


回答2:

Unicode-encoded text files can be opened in the usual way using the OpenTextFile() method of the FileSystemObject class. Just pass True/-1 for the 4th ("format") parameter.

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

To encode your text as UTF-8, you'll need to use the ADO Stream class.

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

For a list of character encodings supported by Windows, look within the following registry key:

HKEY_CLASSES_ROOT\MIME\Database\Charset