如何最好地将UTF-16文件转换为UTF-8?我需要在cmd脚本中使用它。
如何最好地将UTF-16文件转换为UTF-8?我需要在cmd脚本中使用它。
有一个GNU工具recode,您也可以在Windows上使用。
recode utf16..utf8 text.txt
除了Ruby之外,另一种选择是使用C#编写一个小的.NET程序(.NET 1.0可以,尽管2.0更简单 :) - 这是一个相当琐碎的代码。你希望在完全没有其他应用程序的情况下完成吗?如果你想要一些代码来实现它,请添加评论,我会回答...
编辑: 好的,这没有任何错误检查,但是...
using System;
using System.IO;
using System.Text;
class FileConverter
{
static void Main(string[] args)
{
string inputFile = args[0];
string outputFile = args[1];
using (StreamReader reader = new StreamReader(inputFile, Encoding.Unicode))
{
using (StreamWriter writer = new StreamWriter(outputFile, false, Encoding.UTF8))
{
CopyContents(reader, writer);
}
}
}
static void CopyContents(TextReader input, TextWriter output)
{
char[] buffer = new char[8192];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, len);
}
}
}
当然,最简单的方法是将脚本加载到记事本中,然后再使用UTF-8编码保存。这是在“另存为”对话框中的一个选项。
你可以通过内置的PowerShell cmdlet轻松实现这一点,你可以从命令行调用它们:
C:\> powershell -c "Get-Content mytext.txt | Set-Content -Encoding utf8 mytext_utf8.txt"
编辑:显然,如果您已经在PowerShell中,这将变得简单。使用别名也可以简化事情:
> gc mytext.txt | sc -Encoding utf8 mytext_utf8.txt
iconv -f utf-16le -t utf-8 file.txt > newfile.txt
- Ikem Krueger