Sample code for 30+ languages & platforms
Lua

Compressing and Decompressing Files Using Streaming (CompressFile / DecompressFile)

See more Compression Examples

This example demonstrates how to compress a file to a binary format and then restore it using the Chilkat.Compression class. The CompressFile method reads the source file, compresses it using the specified algorithm, and writes the result to a destination file. The DecompressFile method performs the reverse operation, restoring the original file from the compressed data.

Both operations are performed internally in streaming mode, allowing files of any size to be processed efficiently without loading the entire file into memory. The example also includes a simple verification step by comparing file sizes to confirm that the decompressed output matches the original input.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This example assumes the Chilkat API has already been unlocked.
-- See Global Unlock Sample for sample code.

local compress = chilkat.Compression.new()

-- Use the zlib algorithm (recommended for general use)
compress.algorithm = "zlib"

-- ------------------------------------------------------------------
-- Compress a file
-- ------------------------------------------------------------------

local inputFile = "c:/temp/example.txt"
local compressedFile = "c:/temp/example.txt.zlib"

local success = compress:compress_file(inputFile, compressedFile)
if not success then
    print("Compression failed:")
    print(compress.last_error_text)
    return
end

print("File compressed successfully:")
print("  Input:      " .. inputFile)
print("  Compressed: " .. compressedFile)

-- ------------------------------------------------------------------
-- Decompress the file back to its original form
-- ------------------------------------------------------------------

local decompressedFile = "c:/temp/example_restored.txt"

success = compress:decompress_file(compressedFile, decompressedFile)
if not success then
    print("Decompression failed:")
    print(compress.last_error_text)
    return
end

print("File decompressed successfully:")
print("  Output: " .. decompressedFile)

-- ------------------------------------------------------------------
-- Optional: Verify file sizes (basic sanity check)
-- ------------------------------------------------------------------

local fac = chilkat.FileAccess.new()

local originalSize = fac:file_size(inputFile)
local restoredSize = fac:file_size(decompressedFile)

print("Original file size:   " .. originalSize)
print("Restored file size:   " .. restoredSize)

if originalSize == restoredSize then
    print("Sizes match (basic verification successful).")
else
    print("Warning: File sizes differ.")
end