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

How to copy files with Unicode characters in file names in Ruby?

在Windows 7上,我无法从Ruby 1.9.2p290复制名称中具有Unicode字符的文件。

例如,我在目录中有两个文件:

1
2
file
ハリー?ポッターと秘密の部屋

(第二个名称包含日语字符,如果看不到的话)

这是代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
> 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解决方案似乎非常有限。它仅适用于" *"参数:

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


并不是真正的解决方案,但是作为一种解决方法,给出了:

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

有什么原因不能执行此操作:

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


已经有一段时间了,但是我一直在研究同样的问题,而且几乎是很明显的方法。

结果表明,当您在Ruby> = 2.1中调用Dir#entries时,可以指定编码。

1
Dir.entries(path, encoding: Encoding::UTF_8)