ruby - 如何在 Ruby 中复制文件名中带有 Unicode 字符的文件?

标签 ruby unicode utf-8 filesystems

我无法从 Windows 7 上的 Ruby 1.9.2p290 复制名称中包含 Unicode 字符的文件。

比如我在一个目录下有两个文件:

file
ハリー・ポッターと秘密の部屋

(如果看不到,第二个名字包含日文字符)

代码如下:

> entries = Dir.entries(path) - %w{ . .. }
> entries[0]
=> "file"
> entries[1]
=> "???????????????" # <--- what?

> File.file? entries[0]
=> true
> File.file? entries[1]
=> false   # <---  !!! Ruby can not see it and will not copy

> entries[1].encoding.name
=> "Windows-1251"
> Encoding.find('filesystem').name
=> "Windows-1251"

如您所见,我的 Ruby 文件系统编码是“windows-1251”,它是 8 位的,无法处理日文。将 default_externaldefault_internal 编码设置为“utf-8”没有帮助。

如何从 Ruby 复制这些文件?

更新

我找到了一个解决方案。如果我使用 Dir.globDir[] 而不是 Dir.entries,它会起作用。文件名现在以 utf-8 编码返回并且可以复制。

更新 #2

我的 Dir.glob 解决方案似乎非常有限。它仅适用于“*”参数:

Dir.glob("*") # <--- Shows Unicode names correctly
Dir.glob("c:/test/*") # <--- Does not work for Unicode names

最佳答案

与其说是一个真正的解决方案,不如说是一种解决方法,给出:

Dir.glob("*") # <--- Shows Unicode names correctly
Dir.glob("c:/test/*") # <--- Does not work for Unicode names

你有什么理由不能这样做吗:

Dir.chdir("c:/test/")
Dir.glob("*")

?

关于ruby - 如何在 Ruby 中复制文件名中带有 Unicode 字符的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8939287/

相关文章:

python - 获取不以 'u' 为前缀的 python 字符串文字的警告

php - 如何在 HTML、PHP 和 MySQL 中处理日语字符

php - 如何通过 PHPExcel 在 Excel 中读取德语字符 (äöü߀)?

c# - 借助C#读取txt文件(unicode和utf8)

ruby - RVM Gemsets 和 Ruby Gemfile 混淆

ruby-on-rails - rails : When to use many to many assocations?

ruby-on-rails - 多表排序

java - Unicode 组合字符单独打印(不与前一个字符组合)

Perl:将 Unicode 字符串传递给 chr()

ruby - Ruby 的 SHA256 在 Mac 上不工作