【问题标题】:UTF-16 to UTF-8 conversion (for scripting in Windows)UTF-16 到 UTF-8 的转换(用于 Windows 中的脚本)
【发布时间】:2010-09-20 21:23:15
【问题描述】:

将 UTF-16 文件转换为 UTF-8 的最佳方法是什么?我需要在 cmd 脚本中使用它。

【问题讨论】:

    标签: windows utf-8 batch-file cmd utf-16


    【解决方案1】:

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

    recode utf16..utf8 text.txt
    

    【讨论】:

    • 可以从 sourceforge 下载 Windows 版本的“recode”作为“用于 Win32 的 GNU 实用程序”包的一部分:downloads.sourceforge.net/unxutils/…
    • 简短说明 - 这也适用于带有 apt-get install recode 的 ubuntu linux。方便。
    【解决方案2】:

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

    【讨论】:

    【解决方案3】:

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

    【讨论】:

    • 干杯,我可以使用它作为解决方法,但是我的脚本需要进行此转换,我无法手动转换每个文件....
    • 虽然它实际上并没有回答问题,因为它在脚本中不起作用,但它确实解决了我的问题!谢谢
    【解决方案4】:

    也许是iconv

    【讨论】:

      【解决方案5】:

      您可以使用内置的 PowerShell cmdlet 轻松完成此操作,您可以从 cmd 调用它:

      C:\> powershell -c "Get-Content mytext.txt | Set-Content -Encoding utf8 mytext_utf8.txt"
      

      编辑:显然,如果您已经在 powershell 中,这将被简化。使用别名也可以简化事情:

      > gc mytext.txt | sc -Encoding utf8 mytext_utf8.txt
      

      【讨论】:

        【解决方案6】:

        如果您安装了 ruby​​ 发行版,则可以调用 ruby​​ 脚本来处理转换:

        Ruby script to convert file(s) character encoding

        本着同样的精神:Perl script

        在没有脚本支持的情况下,您必须使用 WideCharToMultiByte() 调用像这样C++ source 对其进行编码...

        【讨论】:

          猜你喜欢
          • 2021-01-30
          • 1970-01-01
          • 2015-09-21
          • 2012-05-10
          • 2015-09-19
          • 2019-11-29
          • 2013-09-10
          • 2013-02-25
          相关资源
          最近更新 更多