Sample code for 30+ languages & platforms
React Native Requires Chilkat v11.0.0+

Decompress Large Text File in Blocks

See more Compression Examples

Decompresses a large text file in blocks, and compares the restored (decompressed) file with the original to make sure it's correct.

Chilkat React Native Downloads

React Native
import { Compression, FileAccess } from '@chilkat/react-native'

async function chilkatExample() {
  // This example requires the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  // First, let's compress a text file.
  // We'll then decompress in blocks, and compare the decompressed with the original file.

  // Compress a text file:
  const compress = new Compression();
  compress.algorithm = 'deflate';

  try {
    await compress.compressFileAsync('qa_data/hamlet.xml', 'qa_data/hamlet_compressed.dat');
  } catch {
    console.log(compress.lastErrorText);
    return;
  }

  const fac = new FileAccess();

  // Examine the uncompressed and compressed sizes:
  const originalPath = 'qa_data/hamlet.xml';
  // Note: The FileSize method returns a signed 32-bit integer.  If the file is potentially larger than 2GB, call FileSizeStr instead to return
  // the size of the file as a string, then convert to an integer value.
  console.log(`uncompressed size: ${fac.fileSize(originalPath)}`);
  console.log(`compressed size: ${fac.fileSize('qa_data/hamlet_compressed.dat')}`);

  // Decompress in blocks..
  const facSrc = new FileAccess();
  const facDest = new FileAccess();

  facSrc.openForRead('qa_data/hamlet_compressed.dat');

  // If we compress in 32K chunks, find out how many blocks there will be.
  const blockSize = 32768;
  const numBlocks = facSrc.getNumBlocks(blockSize);

  // Open an output file for the decompressed data.
  const restoredPath = 'qa_output/hamlet_restored.xml';
  try {
    facDest.openForWrite(restoredPath);
  } catch {
    console.log(facDest.lastErrorText);
    return;
  }

  let decompressedStr = '';
  let compressedBytes = new ArrayBuffer(0);

  // Assuming numBlocks > 1
  compress.firstChunk = true;
  compress.lastChunk = false;

  let i = 0;
  while (i < numBlocks) {
    compressedBytes = facSrc.readBlock(i, blockSize);
    decompressedStr = compress.decompressString(compressedBytes);

    facDest.appendText(decompressedStr, 'utf-8');

    i++;

    compress.firstChunk = false;
    if (i === (numBlocks - 1)) {
      compress.lastChunk = true;
    }
  }

  facSrc.fileClose();
  facDest.fileClose();

  // Examine the size of the restored file.
  console.log(`restored size: ${fac.fileSize(restoredPath)}`);

  // Compare the contents of the original with the restored.
  const bEqualContents = fac.fileContentsEqual(restoredPath, originalPath);
  console.log(`Contents Equal: ${bEqualContents}`);
}