将UTF8文本写入文件

时间:2010-05-15 13:20:37

标签: javascript internet-explorer unicode activex internationalization

我使用以下函数将文本保存到文件中(在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编码文本,但结果是乱码。什么是变通方法?

4 个答案:

答案 0 :(得分:5)

试试这个:

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();
}

答案 1 :(得分:2)

在您对true方法的调用中添加第三个参数CreateTextFileSee this page

答案 2 :(得分:1)

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这样的文件中,双击该文件后,它就会运行。

答案 3 :(得分:-1)

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]])