Why are binary files corrupted when zipping them?

你。 提交于 2019-12-05 21:58:12
Matheus Moreira

theglauber's answer is correct. As stated in the documentation of the IO class, which is File's superclass:

Binary file mode. Suppresses EOL <-> CRLF conversion on Windows. And sets external encoding to ASCII-8BIT unless explicitly specified.

Emphasis mine. On Windows, native line endings (\r\n) are implicitly converted to line feeds (\n) when a file is opened in text mode, which probably is what is causing the corruption.

There is also the fact that IO#puts ensures the output ends with a line separator (\r\n on Windows), which is undesirable for binary file formats.

You are also not closing the file returned by File.open. Here is an elegant solution that will fix all these problems:

io.get_output_stream(zip_file_path) do |out|
  out.write File.binread(disk_file_path)
end
theglauber

If this is Windows, you may have to open your output file in binary mode.

For example: io = File.open('foo.zip','wb')

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!