2012-11-22 58 views
0

下面的程序適用於ruby,但在到達帶有特殊字符(如我用於測試的文件,名爲「mão.txt」)的文件時,給我帶來了JRuby問題:使用JRuby無法打開包含特殊字符的文件

# coding: utf-8 

puts "(A) #{__ENCODING__}" 

puts "(B)" + "".encoding.to_s 
puts "(C)" + String.new.encoding.to_s 

Dir.glob("./fixtures/*").each do |f| 
    puts "(D)" + f.encoding.to_s + " " + f 
    File.open(f) 
    g = File.expand_path(f) 
    puts "(E)" + g + " " + g.encoding.to_s 
    File.open(g) 
end 

JRuby的結果是:

(A) UTF-8 
(B)UTF-8 
(C)ASCII-8BIT 
(D)ASCII-8BIT ./fixtures/mão.txt~ 
Errno::ENOENT: No such file or directory - ./fixtures/mão.txt~ 
    initialize at org/jruby/RubyFile.java:315 
     open at org/jruby/RubyIO.java:1176 
     (root) at encoding.rb:10 
     each at org/jruby/RubyArray.java:1612 
     (root) at encoding.rb:8 

我使用Ubuntu 12.10的JRuby 1.7.0和Java 1.7.0_09

我打算有戰爭打包的應用程序ble,所以我擔心命令行參數不是一個選項。

回答

1

這是一個帶有Dir.glob的報告。

+0

我已經提交[補丁](https://github.com/jruby/jruby/pull/407)這個問題是現在已經合併成核心;所以現在問題應該得到解決。 –

1

正如Sebastien所說,這是一個已知的錯誤。

我實際上找到了這個bug的解決方法。而不是使用Dir.glob,在這種情況下,我需要目錄中的每個文件,我可以簡單地使用Dir.entries,它工作正常。

程序可以更改爲:

# coding: utf-8 
path = File.expand_path(File.dirname(__FILE__)) 
puts "(A) #{__ENCODING__}" 

puts "(B)" + "".encoding.to_s 
puts "(C)" + String.new.encoding.to_s 

dir = "#{path}/fixtures/" 
entries = Dir.entries(dir) - ['.', '..'] 
entries.each do |f| 
    puts "(D)" + f.encoding.to_s + " " + f 
    file = "#{dir}/#{f}" 
    puts "(E)" + file.encoding.to_s + " " + file 
    #f.encode("UTF-8") 
    File.open(file) 
    g = File.expand_path(file) 
    puts "(F)" + g + " " + g.encoding.to_s 
    File.open(g) 
end