【问题标题】:Writing UTF8 text to file将 UTF8 文本写入文件
【发布时间】:2026-01-20 13:40:02
【问题描述】:

我正在使用以下函数将文本保存到文件(在 IE-8 w/ActiveX 上)。

function saveFile(strFullPath, strContent)
{
    var fso = new ActiveXObject( "Scripting.FileSystemObject" );

    var flOutput = fso.CreateTextFile( strFullPath, true ); //true for overwrite
    flOutput.Write( strContent );
    flOutput.Close();
}

如果文本完全是 Latin-9,则代码可以正常工作,但当文本甚至包含单个 UTF-8 编码字符时,写入会失败。

ActiveX FileSystemObject 似乎不支持 UTF-8。我首先尝试对文本进行 UTF-16 编码,但结果是乱码。什么是解决方法?

【问题讨论】:

标签: javascript internet-explorer unicode activex internationalization


【解决方案1】:

试试这个:

function saveFile(strFullPath, strContent) {
 var fso = new ActiveXObject("Scripting.FileSystemObject");
 var utf8Enc = new ActiveXObject("Utf8Lib.Utf8Enc");
 var flOutput = fso.CreateTextFile(strFullPath, true); //true for overwrite
 flOutput.BinaryWrite(utf8Enc.UnicodeToUtf8(strContent));
 flOutput.Close();
}

【讨论】:

  • Utf8Lib 凭空而来?我们公司没有安装。
  • ITextStream方法返回的ITextStream对象中没有BinaryWrite方法,Utf8Lib.Utf8Enc是什么?
【解决方案2】:

CreateTextFile 方法有第三个参数,它决定文件是否写成 unicode。你可以这样做:

var flOutput = fso.CreateTextFile(strFullPath,true, true);

有趣的是,早在以前我就创建了这个小脚本来以 unicode 格式保存文件:

Set FSO=CreateObject("Scripting.FileSystemObject")
Value = InputBox ("Enter the path of the file you want to save in Unicode format.")

If Len(Trim(Value)) > 0 Then
    If FSO.FileExists(Value) Then
        Set iFile = FSO.OpenTextFile (Value)
        Data = iFile.ReadAll
        iFile.Close

        Set oFile = FSO.CreateTextFile (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),True,True)
        oFile.Write Data
        oFile.Close

        If FSO.FileExists (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value)) Then
            MsgBox "File successfully saved to:" & vbCrLf & vbCrLf &  FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),vbInformation
        Else
            MsgBox "Unknown error was encountered!",vbCritical
        End If
    Else
        MsgBox "Make sure that you have entered the correct file path.",vbExclamation
    End If
End If

Set iFile = Nothing
Set oFile= Nothing
Set FSO= Nothing

Function GetExtention (Path)
    GetExtention = Right(Path,4)
End Function

注意:这是VBScript代码,您应该将该代码保存在unicode.vbs之类的文件中,然后双击该文件,它将运行。

【讨论】:

  • 不,不会保存为 UTF-8。
【解决方案3】:

在您对CreateTextFile 方法的调用中添加第三个参数trueSee this page.

【讨论】:

  • 它将保存为 UTF-16,而不是 UTF8
【解决方案4】:
function saveFile(strFullPath, strContent) {
    var fso = new ActiveXObject( "Scripting.FileSystemObject" );
    var flOutput = fso.CreateTextFile( strFullPath, true, true ); //true for overwrite // true for unicode
    flOutput.Write( strContent );
    flOutput.Close();
}

object.CreateTextFile(filename[, overwrite[, unicode]])

【讨论】: