在Ruby代码中使用LZMA算法对数据进行压缩和解压缩
截止到目前为止,开源的、以数学原理为基础的、通用的、无损的数据压缩算法中,压缩比最高的,应该就是LZMA了。
在Ruby代码中,可使用ruby-lzma这个库来利用LZMA算法进行数据的压缩和解压缩。这个库的官方网站是: https://github.com/ianlevesque/ruby-lzma 。安装很简单,压缩接口很简单,解压接口也很简单。
以下用几段实例代码来展示ruby-lzma库的使用。
执行以下指令:
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
调用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
调用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
md5sum manifestfulltextcache manifestfulltextcache.decompressed
[g@c ruby.lzma.zzaqse]$ md5sum manifestfulltextcache manifestfulltextcache.decompressed
93f2876b2f120da90223b2cabef07678 manifestfulltextcache
93f2876b2f120da90223b2cabef07678 manifestfulltextcache.decompressed
HxLauncher: Launch Android applications by voice commands