Ruby - Compress a File using Gzip

1. Introduction

File compression is a common method to reduce file size, which helps in saving storage space and accelerating file transfers. In Ruby, one can leverage the built-in Zlib module to compress files using the Gzip format. In this post, we will walk through the process of compressing a file using Gzip in Ruby.

Gzip (GNU zip) is a file format and a software application used for file compression and decompression. It is widely used in UNIX-like operating systems. The Zlib module in Ruby provides methods for creating, reading and writing gzip files.

2. Program Steps

1. Require the zlib library.

2. Open the file you want to compress in binary mode.

3. Create a new gzip writer instance.

4. Write the content of the original file into the gzip writer.

5. Close the gzip writer to ensure that the data is written and the file is compressed.

3. Code Program

# Require the Zlib library
require 'zlib'
# Path of the original file and the compressed file
original_file = 'sample.txt'
compressed_file = 'sample.txt.gz'
# Open the original file in binary mode
File.open(original_file, 'rb') do |file|
  # Create a new gzip writer instance
  Zlib::GzipWriter.open(compressed_file) do |gz|
    # Write the content of the original file into the gzip writer
    gz.write file.read
    # Close the gzip writer
    gz.close
  end
end
puts "File #{original_file} has been compressed to #{compressed_file}."

Output:

File sample.txt has been compressed to sample.txt.gz.

Explanation:

1. require 'zlib': This line imports the Zlib module, enabling the ability to work with gzip compression.

2. original_file = 'sample.txt' and compressed_file = 'sample.txt.gz': These lines specify the paths for the original file and the output compressed file, respectively.

3. File.open(original_file, 'rb') do |file|: This line opens the original file in binary mode, ensuring that the data is read exactly as it is, without any transformations.

4. Zlib::GzipWriter.open(compressed_file) do |gz|: The GzipWriter.open method is used to create a new Gzip writer instance.

5. gz.write file.read: This line reads the content of the original file and writes it to the gzip writer.

6. gz.close: This ensures that the gzip writer is closed, the data is written, and the file is compressed.


Comments