【问题标题】:Can not open files with special characters using JRuby无法使用 JRuby 打开带有特殊字符的文件
【发布时间】:2014-02-14 13:37:15
【问题描述】:

以下程序在 ruby​​ 上运行良好,但在访问具有特殊字符(如我用于测试的文件,称为“mão.txt”)的文件时,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

我打算用 Warble 打包应用程序,所以我担心命令行参数不是一个选项。

【问题讨论】:

    标签: file-io encoding jruby


    【解决方案1】:

    这是一个报告的bugDir.glob

    【讨论】:

    • 我已为此问题提交了patch,该问题现已合并到核心;所以现在应该解决这个问题。
    【解决方案2】:

    正如 Sebastien 所说,这是一个已知的错误。

    我实际上找到了解决此错误的方法。而不是使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多