需要在 vbscript 中将文本文件从 UTF8 转换为 Unicode [英] Need to convert text files to Unicode from UTF8 in vbscript

查看:16
本文介绍了需要在 vbscript 中将文本文件从 UTF8 转换为 Unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个文件夹中有一堆文本文件,我需要将编码更改为 Unicode,而不是手动打开文件并将它们保存为 Unicode,我希望有一个脚本来执行此操作.

I have a bunch of text files in a folder that I need to change the encoding on to Unicode and instead of manually opening the files and saving them as Unicode I would like to have a script to do this.

文件目前采用 UTF-8 编码,我极其有限的脚本能力无法弄清楚这一点.我发现下面的代码可以从 ANSI 转换为 Unicode,当我使用此代码时,它确实将其转换为 Unicode,但它弄乱了字符,因此转换实际上不起作用.有什么想法吗?提前致谢.

The files are currently in UTF-8 encoding and my extremely limited scripting abilities can't figure this one out. I found the code below to convert to Unicode from ANSI and when I use this code it does convert it to Unicode but it messes up the characters so the conversion doesn't actually work. Any thoughts? Thanks in advance.

Set fso = CreateObject("Scripting.FileSystemObject")
Set oFolder = fso.GetFolder("C:	est")
Set oFiles = oFolder.files

For each file in oFiles
If Right(file.Name, 3) = "txt" Then
Set ANSIFile = fso.OpenTextFile(file.path, 1, False, False)
ANSIContent = ANSIFile.ReadAll
Set UNICODEFile = fso.OpenTextFile(file.path, 2, False, True)
UNICODEFile.Write ANSIContent
End If
Next

推荐答案

不幸的是,VBScript 本身不支持这种转换.不过,您可以使用 ADODB.Stream 对象:

Unfortunately VBScript doesn't support this kind of conversion by itself. You can use an ADODB.Stream object, though:

Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 'text
stream.Charset = "utf-8"
stream.LoadFromFile "C:input.txt"
text = stream.ReadText
stream.Close

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:output.txt", 2, True, True)
f.Write text
f.Close

或者更精简一点:

Set fso = CreateObject("Scripting.FileSystemObject")

Set stream = CreateObject("ADODB.Stream")
stream.Open
stream.Type = 2 'text
stream.Charset = "utf-8"
stream.LoadFromFile "C:input.txt"
fso.OpenTextFile("C:output.txt", 2, True, True).Write stream.ReadText
stream.Close

如果要替换现有文件,则必须使用第一个版本并使用相同的文件进行输入和输出.使用这样的循环来遍历文件夹中的所有文件:

If you want to replace the existing file you'll have to use the first version and use the same file for input and output. Use a loop like this to iterate over all files in a folder:

Set fso = CreateObject("Scripting.FileSystemObject")
Set stream = CreateObject("ADODB.Stream")

For Each f In fso.GetFolder("C:sourcefolder").Files
  stream.Open
  stream.Type = 2 'text
  stream.Charset = "utf-8"
  stream.LoadFromFile f.Path
  text = stream.ReadText
  stream.Close

  fso.OpenTextFile(f.Path, 2, True, True).Write text
Next

这篇关于需要在 vbscript 中将文本文件从 UTF8 转换为 Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆