Ruby - Extract a Gzip Compressed File

1. Introduction

Gzip is a widely used method for compressing files, especially on UNIX-like systems. The compressed files not only save storage space but also reduce transfer time when moved across networks. Just as it's crucial to compress files, it's equally important to know how to extract them. In this guide, we will walk through the process of extracting a Gzip compressed file using Ruby.

2. Program Steps

1. Import the zlib module.

2. Specify paths for the compressed file and the output decompressed file.

3. Open the compressed file using Zlib::GzipReader.

4. Read the content from the Gzip reader and write it to the output file.

5. Close the files to ensure all data is written and the file is decompressed.

3. Code Program

# Import the Zlib module
require 'zlib'
# Paths for the compressed file and the output decompressed file
compressed_file = 'sample.txt.gz'
decompressed_file = 'sample_decompressed.txt'
# Open the compressed file using GzipReader
Zlib::GzipReader.open(compressed_file) do |gz|
  # Open the output file in binary mode for writing
  File.open(decompressed_file, 'wb') do |file|
    # Write the decompressed content to the output file
    file.write gz.read
  end
end
puts "File #{compressed_file} has been decompressed to #{decompressed_file}."

Output:

File sample.txt.gz has been decompressed to sample_decompressed.txt.

Explanation:

1. require 'zlib': This imports the Zlib module, giving us access to the gzip-related methods.

2. compressed_file = 'sample.txt.gz' and decompressed_file = 'sample_decompressed.txt': These lines specify the paths for the compressed file and the resulting decompressed file.

3. Zlib::GzipReader.open(compressed_file) do |gz|: The GzipReader.open method is used to open and read the content of the compressed file.

4. File.open(decompressed_file, 'wb') do |file|: This line opens (or creates) the output file in binary write mode.

5. file.write gz.read: This line reads the decompressed content from the gzip reader and writes it to the output file, effectively extracting the original content.


Comments