【问题标题】:Ruby Encoding While File Writing文件写入时的 Ruby 编码
【发布时间】:2018-01-19 00:53:09
【问题描述】:

我有一堆 pdf/txt/msg 文件试图在 ruby​​ 控制台中下载,然后移动到本地目录或重新上传到另一个目的地。

首先,我一直在尝试读取文件并将其写入本地目录,如下所示:

path = File.join 'temp', doc_name
file = File.new(path, 'w')
file << Document.find(123).fetch_file  // this function retrieves and decrypts the file from s3

我得到的异常是:Encoding::UndefinedConversionError: "\xB5" from ASCII-8BIT to UTF-8

我想知道如何才能在文件写入时获得正确的编码,以便我可以下载并打开它。看起来应该是微不足道的,答案可能在解密或s3调用中,但这似乎与文件写入有关。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您需要以二进制格式打开文件以获得正确的编码。

    file = File.new(path, 'wb')
    

    像这样检查编码

    puts file.encoding
    

    它应该是“ASCII-8BIT”。 对你解密的文件内容做同样的事情,它应该是相同的编码,否则你需要像这样转换它。

    Document.find(123).fetch_file.force_encoding('ASCII-8BIT')
    

    您也可以使用File.binread(file)File.binwrite(file, content)

    http://ruby-doc.org/core-2.3.0/IO.html#method-c-binread

    http://ruby-doc.org/core-2.3.0/IO.html#method-c-binwrite

    【讨论】:

    • 我怀疑fetch_file 已经给了他ASCII-8BIT,否则他不会收到该消息;所以force_encoding 应该是不必要的。
    • 彼得,您是一位绅士和一位学者。 Amadan,你是对的,它确实返回了 ASCII-8BIT。我不需要 force_encoding。我在 File.new 上使用 wb 选项就像一个魅力。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    相关资源
    最近更新 更多