UTF-16转换为UTF-8(用于Windows脚本)

15

如何最好地将UTF-16文件转换为UTF-8?我需要在cmd脚本中使用它。

6个回答

24

有一个GNU工具recode,您也可以在Windows上使用。

recode utf16..utf8 text.txt

6
您可以从SourceForge下载“GNU Win32实用程序”包的一部分,其中包括“recode”的Windows版本:http://downloads.sourceforge.net/unxutils/UnxUtils.zip?modtime=1172730504&big_mirror=0 - msanders
2
简短说明 - 这也适用于Ubuntu Linux,只需使用apt-get install recode命令即可。非常方便。 - Danny Staple

15

除了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);
    }
  }
}

我希望有一个实用工具可以直接使用 :) 如果能提供一点代码就非常感激了,谢谢。 - Grzenio
请注意,这里有一个基于该代码的小实用程序:https://github.com/paulroho/ConvertToUtf8。 - paulroho

10

当然,最简单的方法是将脚本加载到记事本中,然后再使用UTF-8编码保存。这是在“另存为”对话框中的一个选项。


3
谢谢,我可以用它作为解决方法,但我的脚本需要进行这种转换,我不能手动转换每个文件... - Grzenio
1
虽然它并没有真正回答问题,因为它在脚本中不起作用,但它确实解决了我的问题!谢谢。 - davidreedernst

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

7
也许可以使用iconv

1
对于所有想知道如何完成此操作的人:iconv -f utf-16le -t utf-8 file.txt > newfile.txt - Ikem Krueger

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接