通过系统从Ruby 1.8.7调用iconv将文件从utf-16转换为utf-8

问题描述:

这就是我得到的:

path_js = 'path/to/a/js/file.js'
path_new_js = 'path/where/the/converted/file/should/go.js'
puts('iconv -f utf-16le -t utf-8 ' + path_js + ' > ' + path_new_js)
system('iconv -f utf-16le -t utf-8 ' + path_js + ' > ' + path_new_js)

puts语句的输出为:

The output of the puts statement is:

iconv -f utf-16le -t utf-8 path/to/1-1-2_E1_MC105.js > compiled/path/to/1-1-2_E1_MC105.js

如果我在终端中复制并粘贴相同的行,则转换成功完成,但是当它在我的ruby脚本中运行时,将使用与原始文件相同的编码创建新文件(在这种情况下为utf-16) .关于缺失/错误的任何想法吗?

If I copy-paste that exact same line in my terminal the conversion takes place successfully but when it runs inside my ruby script, the new file is created with the same encoding as the original file (utf-16 in this case). Any ideas on what's missing/wrong?

干杯!

更新:我在Mac OS X Snow Leopard上,并且使用ruby 1.8.7(系统默认值)和1.9.2(使用RVM安装)尝试了相同的脚本.我还尝试了以下方法:

Update: I'm on Mac OS X Snow Leopard and I tried the same script using ruby 1.8.7 (system default) and 1.9.2 (Installed using RVM). I also tried the following:

f = File.open(path_js,'rb')
js = f.read
f.close
new_js = Iconv.conv('utf-8', 'utf-16', js)
File.open(path_new_js,'w'){|f| f.write(new_js)}

结果相同:S

那应该等效于直接运行命令,因此请确保它实际上在正确运行.如果执行中出现错误,system将返回false.

That should be the equivalent of running the command directly, so be sure it's actually running correctly. system will return false if there's an error in execution.

您也可以使用Ruby中的iconv库直接执行此操作,而不需要命令行工具.这样可以提供更多的控制权.

You can also use the iconv library in Ruby to do it directly instead of needing the command line tool. That may offer more control.