Ruby 过早 EOF?
我正在尝试用 Ruby 将一个文件写入另一个文件,但输出似乎过早停止。
输入文件 - 带有 base64 嵌入字体的大型 CSS 文件
输出文件 - 基本 html 文件。
#write some HTML before the CSS (works)
...
#write the external CSS (doesn't work, output finished prematurely)
while !ext_css_file.eof()
out_file.puts(ext_css_file.read())
end
...
#write some HTML after the CSS (works)
生成的文件基本上是一个有效的 HTML 文件,带有截断的 CSS(在嵌入字体的中间)
当对 read() 的结果执行 put 时,我得到相同的结果: CSS 文件只读到此最后一个字符串:“RMSHhoPCAGt/mELDBESFBQSggGfAgESKCUAAAAAAAwAlgABAAAAAAABAAUADAABAAAAAAAC”
I'm trying to write one file into another one in Ruby, but the output seems to stop prematurely.
Input file - large CSS file with base64 embedded fonts
Output file - basic html file.
#write some HTML before the CSS (works)
...
#write the external CSS (doesn't work, output finished prematurely)
while !ext_css_file.eof()
out_file.puts(ext_css_file.read())
end
...
#write some HTML after the CSS (works)
The resulting file is basically a valid HTML file, with a truncated CSS (in the middle of an embedded font)
When doing a puts on the result of read(), I get the same result: The CSS file is read only up to this last string: "RMSHhoPCAGt/mELDBESFBQSggGfAgESKCUAAAAAAAwAlgABAAAAAAABAAUADAABAAAAAAAC"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果不深入了解 CSS 文件实际包含的内容,就很难提供详细的解决方案。根据上面的代码,我会尝试这样的方法:
我认为您不需要
.eof
检查,因为read
方法读取并返回整个文件内容,或者空字符串,如果位于文件末尾则为 nil。请参阅此处: http://apidock.com/ruby/IO/read我倾向于阅读并写入相同类型的数据。例如,如果我使用 puts 将数据写入新文件,我将使用 readlines 读取数据。如果我使用
write
写入二进制数据,我将使用read
读取数据。我会与字符串或字节保持一致,而不是混合两者。尝试这样的事情......
It is difficult to provide a detailed solution without more insight into what the CSS file actually contains. Based on your code above, I would try something like this instead:
I don't think you need the
.eof
check because theread
method reads and returns the entire file contents, or an empty string or nil if at the end of file. See here: http://apidock.com/ruby/IO/readI would tend to read and write the same type of data. For instance if I were writing data into the new file using
puts
, I would read data usingreadlines
. If I were writing binary data usingwrite
, I would read the data usingread
. I would be consistent with either strings or bytes and not mix the two.Try something like this...