StupidBeauty
Read times:3809Posted at:Thu Jul 23 05:23:02 2020 - no title specified

Ruby代码中使用LZMA算法对数据进行压缩和解压缩

1 概述

截止到目前为止,开源的、以数学原理为基础的、通用的、无损的数据压缩算法中,压缩比最高的,应该就是LZMA了。

在Ruby代码中,可使用ruby-lzma这个库来利用LZMA算法进行数据的压缩和解压缩。这个库的官方网站是: https://github.com/ianlevesque/ruby-lzma 。安装很简单,压缩接口很简单,解压接口也很简单。

以下用几段实例代码来展示ruby-lzma库的使用。

2 安装

执行以下指令:

sudo gem install ruby-lzma

bash-4.4# sudo gem install ruby-lzma
Building native extensions. This could take a while...
Successfully installed ruby-lzma-0.4.3
Parsing documentation for ruby-lzma-0.4.3
Done installing documentation for ruby-lzma after 0 seconds
1 gem installed

3 压缩

调用LZMA.compress方法。

以下是一段完整示例代码:

#!/usr/bin/env ruby

require 'lzma'

originalFileContent=File.read('manifestfulltextcache')

puts("Original file length: #{originalFileContent.bytesize}")

compressedContent=LZMA.compress(originalFileContent)

puts("Compressed content length: #{compressedContent.bytesize}")

compressedFile=File.new('manifestfulltextcache.compressed', 'wb')

compressedFile.syswrite(compressedContent)

compressedFile.close

运行结果:

[g@c ruby.lzma.zzaqse]$ ./compress.zzaqsc.rb    
Original file length: 2266
Compressed content length: 634

4 解压缩

调用LZMA.decompress方法。

以下是一段完整示例代码:

#!/usr/bin/env ruby

require 'lzma'

compressedContent=File.read('manifestfulltextcache.compressed')

puts("Compressed content length: #{compressedContent.bytesize}")

originalFileContent=LZMA.decompress(compressedContent)

puts("Decompressed file length: #{originalFileContent.bytesize}")

decompressedFile=File.new('manifestfulltextcache.decompressed', 'wb')

decompressedFile.syswrite(originalFileContent)

decompressedFile.close

运行结果:

[g@c ruby.lzma.zzaqse]$ ./decompress.zzaqsb.rb  
Compressed content length: 634
Decompressed file length: 2266

5 验证解压缩后的内容是否与压缩前的原始内容相同

md5sum manifestfulltextcache manifestfulltextcache.decompressed

[g@c ruby.lzma.zzaqse]$ md5sum manifestfulltextcache manifestfulltextcache.decompressed  
93f2876b2f120da90223b2cabef07678  manifestfulltextcache
93f2876b2f120da90223b2cabef07678  manifestfulltextcache.decompressed

Your opinions
Your name:Email:Website url:Opinion content:
- no title specified

HxLauncher: Launch Android applications by voice commands

 
Recent comments
2017年4月~2019年4月垃圾短信排行榜Posted at:Thu Sep 26 04:51:48 2024
Qt5.7文档翻译:QWebEngineCookieStore类,QWebEngineCookieStore ClassPosted at:Fri Aug 11 06:50:35 2023盲盒kill -9 18289 Grebe.20230517.211749.552.mp4