Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Working with Bzip2

Decompress a bzip2 file

bzip2-badge cat-compression-badge

Decompresses a single bzip2-compressed file input.txt.bz2 into input.txt in the current working directory.

Wraps a File in a BzDecoder and copies the decompressed bytes into the destination file with io::copy.

use bzip2::read::BzDecoder;
use std::fs::File;
use std::io;

fn main() -> io::Result<()> {
    let input = File::open("input.txt.bz2")?;
    let mut decoder = BzDecoder::new(input);
    let mut output = File::create("input.txt")?;
    io::copy(&mut decoder, &mut output)?;
    Ok(())
}

Compress a file with bzip2

bzip2-badge cat-compression-badge

Compresses input.txt into input.txt.bz2 in the current working directory.

Wraps a File in a BzEncoder configured with a Compression level, then copies the contents of the source file into the encoder with io::copy, transparently compressing the data as it is written to input.txt.bz2.

use bzip2::Compression;
use bzip2::write::BzEncoder;
use std::fs::File;
use std::io;

fn main() -> io::Result<()> {
    let mut input = File::open("input.txt")?;
    let output = File::create("input.txt.bz2")?;
    let mut encoder = BzEncoder::new(output, Compression::best());
    io::copy(&mut input, &mut encoder)?;
    encoder.finish()?;
    Ok(())
}