# CommonsCompress
**Repository Path**: chenwenjiehw/CommonsCompress
## Basic Information
- **Project Name**: CommonsCompress
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: Apache-2.0
- **Default Branch**: master
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 34
- **Created**: 2022-11-01
- **Last Updated**: 2022-11-02
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# commons-compress
## 简介
commons-compress组件定义了一个用于处理压缩和存档格式的 API,包含bzip2、gzip、lzma、xz、Snappy、LZ4、Brotli、DEFLATE、Zstandard 和 ar、cpio、tar、zip、dump、7z等格式的压缩/解压功能。

## 下载
```
  npm install @ohos/commons-compress --save
```
OpenHarmony npm环境配置等更多内容,请参照 [如何安装OpenHarmony npm包](https://gitee.com/openharmony-tpc/docs/blob/master/OpenHarmony_npm_usage.md) 。
## 使用说明
### 配置全局路径
需要在MainAbility文件配置全局路径
``` javascript
globalThis.context = this.context;
```
### zip 压缩功能
指定文件夹路径压缩zip文件夹。
``` javascript
import fileio from '@ohos.fileio';
import { zipCompress } from '@ohos/commons-compress';
  jsZipTest(): void {
    try{
      var data = globalThis.context.filesDir
        zipCompress(data + '/' + this.newFolder, data + '/' + this.newFolder + '.zip').then((isSuccess) => {
          if (isSuccess) {
            AlertDialog.show({ title: '压缩成功',
              message: '请查看手机路径 ' + data + '/',
              confirm: { value: 'OK', action: () => {
                this.isDeCompressGZipShow = true
              } }
            })
          }
        })
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### zip 解压功能
指定文件夹路径解压zip文件夹。
``` javascript
import fileio from '@ohos.fileio';
import { zipDeCompress } from '@ohos/commons-compress';
  unJsZipTest(): void {
    try{
      var data = globalThis.context.filesDir
        zipDeCompress(data + '/' + this.newFolder + '.zip', data + '/newTarget')
          .then((isZipDecompree) => {
            if (isZipDecompree) {
              AlertDialog.show({ title: '解缩成功',
                message: '请查看手机路径 ' + data + "/newTarget",
                confirm: { value: 'OK', action: () => {
                } }
              })
            }
          })
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### gzip 压缩功能
指定文件夹路径压缩gz文件夹。
``` javascript
import {gzipFile} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  gzipFileTest(): void {
    try{
      var data = globalThis.context.filesDir
        console.info('directory obtained. Data:' + data);
        gzipFile(data + '/hello.txt', data + '/test.txt.gz')
          .then((isSuccess) => {
            if (isSuccess) {
              AlertDialog.show({ title: '压缩成功',
                message: '请查看手机路径 ' + data + '/test.txt.gz',
                confirm: { value: 'OK', action: () => {
                  this.isDeCompressGZipShow = true
                } }
              })
            }
          });
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### gzip 解压功能
指定文件夹路径解压gz文件夹。
``` javascript
import {unGzipFile} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  unGzipFileTest(): void {
    try{
      var data = globalThis.context.filesDir
        unGzipFile(data + '/test.txt.gz', data + '/test.txt')
          .then((isSuccess) => {
            if (isSuccess) {
              AlertDialog.show({ title: '解缩成功',
                message: '请查看手机路径 ' + data + '/test.txt',
                confirm: { value: 'OK', action: () => {
                } }
              })
            }
          });
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### xz 压缩功能
指定文件夹路径压缩XZ文件夹。
```javascript
import {File, OutputStream, InputStream, IOUtils, CompressorStreamFactory, CompressorOutputStream } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
 
  testXZCreation(): void {
    try{
      var data = globalThis.context.filesDir
        console.info('directory obtained. Data:' + data);
        let input = new File(data, "/hello.txt");
        let output = new File(data, "/hello.txt.xz");
        let out: OutputStream = new OutputStream();
        let input1: InputStream = new InputStream();
        out.setFilePath(output.getPath());
        input1.setFilePath(input.getPath());
        let cos: CompressorOutputStream = new CompressorStreamFactory(false). createCompressorOutputStream("xz", out)
        IOUtils.copyStream(input1, cos);
        cos.close();
        input1.close()
        AlertDialog.show({ title: '压缩成功',
          message: '请查看手机路径 ' + data + '/hello.txt.xz',
          confirm: { value: 'OK', action: () => {
            this.isDeCompressBzip2Show = true
          } }
        })
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### xz 解压功能
指定文件夹路径解压XZ文件夹。
```javascript
import {File, OutputStream, InputStream, IOUtils, CompressorStreamFactory, CompressorInputStream} from '@ohos/commons-compress' 
import fileio from '@ohos.fileio';
 
  unXZFileTest(): void {
    try{
      var data = globalThis.context.filesDir
        let input = new File(data, "/hello.txt.xz");
        let output = new File(data, "/hello1.txt");
        let out: OutputStream = new OutputStream();
        let input1: InputStream = new InputStream();
        out.setFilePath(output.getPath());
        input1.setFilePath(input.getPath());
        let inputs: CompressorInputStream = new CompressorStreamFactory(false). createCompressorNameInputStream("xz", input1)
        IOUtils.copyStream(inputs, out);
        out.close();
        input1.close();
        AlertDialog.show({ title: '解缩成功',
          message: '请查看手机路径 ' + data + '/hello1.txt',
          confirm: { value: 'OK', action: () => {
          } }
        })
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### Z 解压功能
指定文件夹路径解压Z文件夹。
```javascript
import {File, OutputStream, InputStream, IOUtils, CompressorInputStream, CompressorStreamFactory} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  unZFileTest(): void {
    try{
      var data = globalThis.context.filesDir
        let inputStream: InputStream = new InputStream();
        inputStream.setFilePath(data + '/bla.tar.Z');
        let fOut: OutputStream = new OutputStream();
        fOut.setFilePath(data + '/bla.tar');
        let input: CompressorInputStream = new CompressorStreamFactory(false). createCompressorNameInputStream("z", inputStream);
        IOUtils.copyStream(input, fOut);
        inputStream.close();
        fOut.close();
        AlertDialog.show({ title: '解缩成功',
          message: '请查看手机路径 ' + data + '/bla.tar',
          confirm: { value: 'OK', action: () => {
          } }
        })
       }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### zstd 压缩解压功能
指定文件夹路径压缩解压zstd 文件夹。
```javascript
import {ZstdCompressor, IOUtils,InputStream,OutputStream,File,ZstdDecompressor,System} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
	compressedSize: number = 0;
  	compressed: Int8Array;
  	original: Int8Array;
//zstd压缩功能
  testZstdCompressed(): void {
     try{
      var data = globalThis.context.filesDir
        console.info('directory obtained. Data:' + data);
        let compressor = new ZstdCompressor();
        let output = new File(data, "/hello.txt.zst");
        let input = new File(data, "/hello.txt");
        let input1 = new InputStream();
        let out = new OutputStream();
        input1.setFilePath(input.getPath());
        out.setFilePath(output.getPath());
        this.original = new Int8Array(input1._endPosition)
        IOUtils.readFull(input1, this.original);
        let maxCompressLength: number = compressor. maxCompressedLength(this.original.length);
        this.compressed = new Int8Array(maxCompressLength);
        this.compressedSize = compressor.getZstdFrameCompress(this.original, 0, this.original.length, this.compressed, 0, this.compressed.length);
        out.writeBytes(this.compressed);
        out.close()
        input1.close();
        AlertDialog.show({ title: '压缩成功',
          message: '请查看手机路径 ' + data + '/hello.txt.zstd',
          confirm: { value: 'OK', action: () => {
            this.isDeCompressBzip2Show = true
          } }
        })
     }catch(error){
       console.error('File to obtain the file directory. Cause: ' + error.message);
     }
  }
  
  //zstd解压功能
  testZstdDecompressed() {
     try{
      var data = globalThis.context.filesDir
        let compressor = new ZstdDecompressor();
        let output = new File(data, "/newhello.txt");
        let out = new OutputStream();
        out.setFilePath(output.getPath());
        let decompressed: Int8Array = new Int8Array(this.original.length);
        let compressedSize: number = compressor.decompress(this.compressed, 0, this.compressedSize, decompressed, 0, decompressed.length);
        out.writeBytes(decompressed)
        out.close()
        AlertDialog.show({ title: '解压成功',
          message: '请查看手机路径 ' + data + '/newhello.txt',
          confirm: { value: 'OK', action: () => {
            this.isDeCompressBzip2Show = true
          } }
        })
     }catch(error){
       console.error('File to obtain the file directory. Cause: ' + error.message);
     }
  }
```
### ar 压缩功能
指定文件夹路径压缩ar文件夹。
```javascript
import { ArchiveEntry, ArchiveUtils, ArArchiveInputStream, ArArchiveEntry, ArchiveStreamFactory, ArchiveOutputStream, InputStream, File,OutputStream,IOUtils} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  jsArTest(): void {
    try{
      var data = globalThis.context.filesDir
        this.testArArchiveCreation(data)
    }catch(error){
      console.error(error.message);
    }
  }
  testArArchiveCreation(data: string) {
    let output: File = new File(data, this.newFolder + '.ar');
    let file1: File = new File(data + '/' + this.newFolder, 'test1.xml');
    let out: OutputStream = new OutputStream();
    let input1: InputStream = new InputStream();
    out.setFilePath(output.getPath());
    input1.setFilePath(file1.getPath());
    let os: ArchiveOutputStream = ArchiveStreamFactory.DEFAULT.createArchiveOutputStream("ar", out, "");
    os.putArchiveEntry(new ArArchiveEntry("test1.xml", Long.fromNumber(file1.length()), 0, 0,
      ArArchiveEntry.DEFAULT_MODE, Long.fromNumber(new Date().getTime() / 1000)));
    IOUtils.copyStream(input1, os);
    os.closeArchiveEntry();
    os.close();
    AlertDialog.show({ title: '压缩成功',
      message: '请查看手机路径 ' + data + '/',
      confirm: { value: 'OK', action: () => {
        this.isDeCompressGArShow = true
      } }
    })
  }
```
### ar 解压功能
指定文件夹路径解压ar文件夹。
```javascript
import { ArchiveEntry, ArchiveUtils, ArArchiveInputStream, ArArchiveEntry, ArchiveStreamFactory, ArchiveOutputStream, InputStream, File,OutputStream,IOUtils} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  jsUnArTest(): void {
    try{
      var data = globalThis.context.filesDir
        this.testReadLongNamesBSD(data)
    }catch(error){
      console.error( error.message);
    }
  }
  testReadLongNamesBSD(data: string): void {
    let inFile: File = new File(data + '/' + this.newFolder, "longfile_bsd.ar");
    let input: InputStream = new InputStream();
    input.setFilePath(inFile.getPath());
    let s: ArArchiveInputStream = new ArArchiveInputStream(input);
    let tarArchiveEntry: ArchiveEntry = null;
    while ((tarArchiveEntry = s.getNextEntry()) != null) {
      let name: string = tarArchiveEntry.getName();
      let tarFile: File = new File(data + '/' + this.newFolder, name);
      if (name.indexOf('/') != -1) {
        try {
          let splitName: string = name.substring(0, name.lastIndexOf('/'));
          fileio.mkdirSync(data + '/' + this.newFolder + '/' + splitName);
        } catch (err) {
        }
      }
      let fos: OutputStream = null;
      try {
        fos = new OutputStream();
        fos.setFilePath(tarFile.getPath())
        let read: number = -1;
        let buffer: Int8Array = new Int8Array(1024);
        while ((read = s.readBytes(buffer)) != -1) {
          fos.writeBytesOffset(buffer, 0, read);
        }
      } catch (e) {
        throw e;
      } finally {
        fos.close();
      }
    }
    AlertDialog.show({ title: '解压成功',
      message: '请查看手机路径 ' + data + '/' + this.newFolder,
      confirm: { value: 'OK', action: () => {
      } }
    })
  }
```
### brotli 解压功能
指定文件夹路径解压brotli文件夹。
```javascript
import { CompressorInputStream,CompressorStreamFactory,ArchiveInputStream,ArchiveStreamFactory,ArchiveEntry,InputStream,File,OutputStream,IOUtils} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
 
  brotilTest(): void {
    try{
      var data = globalThis.context.filesDir
        this.generateTextFile(data, '/bla.tar.br', compressData)
        let input = new File(data, "/bla.tar.br");
        let output = new File(data, "/bla.tar");
        let out: OutputStream = new OutputStream();
        let input1: InputStream = new InputStream();
        out.setFilePath(output.getPath());
        input1.setFilePath(input.getPath());
        let inputs: CompressorInputStream = new CompressorStreamFactory().createCompressorNameInputStream("br", input1)
        IOUtils.copyStream(inputs, out);
        out.close();
        input1.close();
        AlertDialog.show({ title: '解缩成功',
          message: '请查看手机路径 ' + data + '/bla.tar',
          confirm: { value: 'OK', action: () => {
          } }
        })
      }catch(error){
        console.error('File to obtain the file directory. Cause: ' + error.message);
      }
  }
  generateTextFile(data: string, fileName: string, arr: Int8Array | Int32Array): void {
    let srcPath = data;
    try {
      fileio.mkdirSync(srcPath);
    } catch (err) {
    }
    const writer = fileio.openSync(srcPath + fileName, 0o102, 0o666);
    fileio.writeSync(writer, arr.buffer);
    fileio.closeSync(writer);
  }
```
### bzip2 压缩功能
指定文件夹路径压缩bzip2文件夹。
```javascript
import { CompressorInputStream,CompressorStreamFactory,InputStream,OutputStream,IOUtils,CompressorOutputStream} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  bzip2FileTest(): void {
    try{
      var data = globalThis.context.filesDir
        console.info('directory obtained. Data:' + data);
        let inputStream: InputStream = new InputStream();
        inputStream.setFilePath(data + '/hello.txt');
        let fOut: OutputStream = new OutputStream();
        fOut.setFilePath(data + '/hello.txt.bz2');
        let cos: CompressorOutputStream = new CompressorStreamFactory(false).createCompressorOutputStream("bzip2", fOut);
        IOUtils.copyStream(inputStream, cos);
        cos.close();
        inputStream.close();
        AlertDialog.show({ title: '压缩成功',
          message: '请查看手机路径 ' + data + '/hello.txt.gz',
          confirm: { value: 'OK', action: () => {
            this.isDeCompressBzip2Show = true
          } }
        })
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### bzip2 解压功能
指定文件夹路径解压bzip2文件夹。
```javascript
import { CompressorInputStream,CompressorStreamFactory,InputStream,OutputStream,IOUtils,CompressorOutputStream} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  unBzip2FileTest(): void {
    try{
      var data = globalThis.context.filesDir
        let inputStream: InputStream = new InputStream();
        inputStream.setFilePath(data + '/hello.txt.bz2');
        let fOut: OutputStream = new OutputStream();
        fOut.setFilePath(data + '/hello.txt');
        let input: CompressorInputStream = new CompressorStreamFactory(false).createCompressorNameInputStream("bzip2", inputStream);
        IOUtils.copyStream(input, fOut);
        inputStream.close();
        fOut.close();
        AlertDialog.show({ title: '解缩成功',
          message: '请查看手机路径 ' + data + '/hello.txt',
          confirm: { value: 'OK', action: () => {
          } }
        })
      }catch(error){
        console.error('File to obtain the file directory. Cause: ' + error.message);
      }
  }
```
### lz4 压缩功能
指定文件夹路径压缩lz4文件夹。
``` javascript
 import {lz4Compressed} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  lz4CompressedTest(): void {
    try{
      var data = globalThis.context.filesDir
        let timer1 = System.currentTimeMillis().toString()
        console.info(this.TAG + timer1)
        lz4Compressed(data + '/bla.tar', data + '/bla.tar.lz4')
        let timer2: string = System.currentTimeMillis().toString()
        console.info(this.TAG + timer2)
        AlertDialog.show({ title: '压缩成功',
          message: '请查看手机路径 ' + data + '/test.txt.lz4',
          confirm: { value: 'OK', action: () => {
            this.isDeCompressLz4Show = true
          } }
        })
      }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### lz4 解压功能
指定文件夹路径解压lz4文件夹。
``` javascript
import {lz4Decompressed} from '@ohos/commons-compress'  
import fileio from '@ohos.fileio';
 
  lz4DecompressedTest(): void {
    try{
      var data = globalThis.context.filesDir
        let timer1 = System.currentTimeMillis().toString()
        console.info(this.TAG + timer1)
        lz4Decompressed(data + '/bla.tar.lz4-framed.lz4', data + '/bla.tar')
        let timer2: string = System.currentTimeMillis().toString()
        console.info(this.TAG + timer2)
        AlertDialog.show({ title: '解缩成功',
          message: '请查看手机路径 ' + data + '/test2.txt',
          confirm: { value: 'OK', action: () => {
          } }
        })
      }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### lzma,sevenz7 压缩功能
指定文件夹路径压缩lzma,sevenz7文件夹。
``` javascript
  import {Decoder, Encoder,InputStream,OutputStream,Exception,System } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
   encoder(path) {
    console.info(this.TAG + '开始')
    let inputStream: InputStream = new InputStream();
    let outputStream: OutputStream = new OutputStream();
    outputStream.setFilePath(path + '/test.xml.lzma')
    inputStream.setFilePath(path + '/test.xml')
    let stat = fileio.statSync(path + '/test.xml');
    let encoder: Encoder = new Encoder();
    if (!encoder.SetAlgorithm(2))
    return
    if (!encoder.SetDictionarySize(1 << 23))
    return
    if (!encoder.SetNumFastBytes(128))
    return
    if (!encoder.SetMatchFinder(1))
    return
    if (!encoder.SetLcLpPb(3, 0, 2))
    return
    encoder.SetEndMarkerMode(false);
    encoder.WriteCoderProperties(outputStream);
    let fileSize: Long = Long.fromNumber(stat.size);
    for (let i = 0; i < 8; i++) {
      outputStream.write(fileSize.shiftRightUnsigned(8 * i).toInt() & 0xFF);
    }
    encoder.Code(inputStream, outputStream, Long.fromNumber(-1), Long.fromNumber(-1), null);
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    console.info(this.TAG + '结束')
  }
```
### lzma,sevenz7 解压功能
指定文件夹路径解压lzma,sevenz7文件夹。
``` javascript
import {Decoder, Encoder,InputStream,OutputStream,Exception,System } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
decoder(path) {
    let decoder: Decoder = new Decoder();
    let inputStream: InputStream = new InputStream();
    inputStream.setFilePath(path + '/test.xml.lzma')
    let outputStream: OutputStream = new OutputStream();
    outputStream.setFilePath(path + '/test.xml')
    let propertiesSize = 5;
    let properties: Int8Array = new Int8Array(propertiesSize);
    if (inputStream.readBytesOffset(properties, 0, propertiesSize) != propertiesSize)
    throw new Exception("input .lzma file is too short");
    if (!decoder.SetDecoderProperties(properties))
    throw new Exception("Incorrect stream properties");
    let outSize: Long = Long.fromNumber(0);
    for (let i = 0; i < 8; i++) {
      let v: number = inputStream.read();
      if (v < 0)
      throw new Exception("Can't read stream size");
      outSize = outSize.or(Long.fromNumber(v).shiftLeft(8 * i));
    }
    if (!decoder.Code(inputStream, outputStream, outSize))
    throw new Exception("Error in data stream");
    outputStream.flush();
    outputStream.close();
    inputStream.close();
  }
```
### tar 压缩功能
指定文件夹路径解压tar文件夹。
``` javascript
import { File, InputStream, OutputStream, ArchiveStreamFactory, TarArchiveEntry, IOUtils } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  jsTarTest(): void {
    try{
        this.testArArchiveCreation(globalThis.context.filesDir);
    }catch(error){
    }
  }
testArArchiveCreation(data: string) {
    try {
      let output: File = new File(data, this.newFolder + '.tar');
      let file1: File = new File(data + '/' + this.newFolder, 'test1.xml');
      let input1: InputStream = new InputStream();
      input1.setFilePath(file1.getPath());
      let out: OutputStream = new OutputStream();
      out.setFilePath(output.getPath());
      let os: ArchiveOutputStream = ArchiveStreamFactory.DEFAULT.createArchiveOutputStream ("tar", out);
      let entry: TarArchiveEntry = new TarArchiveEntry();
      entry.tarArchiveEntryPreserveAbsolutePath2("testdata/test1.xml", false);
      entry.setModTime(Long.fromNumber(0));
      entry.setSize(Long.fromNumber(file1.length()));
      entry.setUserId(0);
      entry.setGroupId(0);
      entry.setUserName("avalon");
      entry.setGroupName("excalibur");
      entry.setMode(0o100000);
      os.putArchiveEntry(entry);
      IOUtils.copyStream(input1, os);
      os.closeArchiveEntry();
      os.close();
      AlertDialog.show({ title: '压缩成功',
        message: '请查看手机路径 ' + data + '/',
        confirm: { value: 'OK', action: () => {
          this.isDeCompressTarShow = true
        } }
      })
    } catch (e) {
      console.error("testArArchiveCreation " + e);
    }
  }
```
### tar 解压功能
指定文件夹路径解压tar文件夹。
``` javascript
import { File, InputStream, OutputStream, TarArchiveInputStream, TarConstants, TarArchiveEntry } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  jsUnTarTest(): void {
    try{
        this.testUnCompressTar(globalThis.context.filesDir);
      }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
testUnCompressTar(data: string) {
    let input: File = new File(data, this.newFolder + '.tar');
    let input1: InputStream = new InputStream();
    input1.setFilePath(input.getPath());
    let tais: TarArchiveInputStream = new TarArchiveInputStream(input1, TarConstants.DEFAULT_BLKSIZE,
      TarConstants.DEFAULT_RCDSIZE, null, false);
    let tarArchiveEntry: TarArchiveEntry = null;
    while ((tarArchiveEntry = tais.getNextTarEntry()) != null) {
      let name: string = tarArchiveEntry.getName();
      let tarFile: File = new File(data + '/' + this.newFolder, name);
      if (name.indexOf('/') != -1) {
        try {
          let splitName: string = name.substring(0, name.lastIndexOf('/'));
          fileio.mkdirSync(data + '/' + this.newFolder + '/' + splitName);
        } catch (err) {
        }
      }
      let fos: OutputStream = null;
      try {
        fos = new OutputStream();
        fos.setFilePath(tarFile.getPath())
        let read: number = -1;
        let buffer: Int8Array = new Int8Array(1024);
        while ((read = tais.readBytes(buffer)) != -1) {
          fos.writeBytesOffset(buffer, 0, read);
        }
        AlertDialog.show({ title: '解压成功',
          message: '请查看手机路径 ' + data + '/' + this.newFolder,
          confirm: { value: 'OK', action: () => {
            this.isDeCompressTarShow = true
          } }
        })
      } catch (e) {
        throw e;
      } finally {
        fos.close();
      }
    }
  }
```
### snappy 压缩解压功能
指定文件夹路径压缩解压sz文件夹。
``` javascript
import { snappyCompress } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  @State newfolder: string = 'newfolder'
  @State newfile: string = 'bla.txt'
  @State newfile1: string = 'bla1.txt'
  snappyJsTest(value) {
    try{
      var data = globalThis.context.filesDir
        if (value) {
          let path = data + '/' + this.newfolder
          console.log('snappyCompress');
          snappyCompress(path, this.newfile)
            .then(() => {
              AlertDialog.show({ title: '压缩成功',
                message: '请查看手机路径 ' + data + '/' + this.newfolder + '/' + this.newfile + '.sz',
                confirm: { value: 'OK', action: () => {
                  this.isDeCompressSnappyShow = true
                } }
              })
            });
        } else {
          console.log('snappyUncompress');
          snappyUncompress(data, this.newfolder, this.newfile, this.newfile1)
            .then(() => {
              AlertDialog.show({ title: '解缩成功',
                message: '请查看手机路径 ' + data + '/' + this.newfile1,
                confirm: { value: 'OK', action: () => {
                } }
              })
            });
        }
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### dump 解压功能
指定文件夹路径解压dump文件夹。
``` javascript
import { File, InputStream, OutputStream, ArchiveStreamFactory, ArchiveInputStream, ArchiveEntry, IOUtils } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
jsDumpTest(): void {
     this.testDumpUnarchiveAll(globalThis.context.filesDir,'dump/bla.dump')
}
testDumpUnarchiveAll(data: string, archive: string): void {
    let file1: File = new File(data, archive);
    //    fileio.mkdirSync(data+'/lost+found')
    let input1: InputStream = new InputStream();
    input1.setFilePath(file1.getPath());
    let input2: ArchiveInputStream = null;
    input2 = ArchiveStreamFactory.DEFAULT.createArchiveInputStream("dump", input1, null);
    let entry: ArchiveEntry = input2.getNextEntry();
    while (entry != null) {
      let out: OutputStream = new OutputStream();
      let name: string = entry.getName().toString();
      let archiveEntry: File = new File(data, name);
      archiveEntry.getParentFile().getPath();
      if (entry.isDirectory()) {
        let splitName: string = name.substring(0, name.lastIndexOf('/'));
        try {
          fileio.mkdirSync(data + '/' + splitName);
        } catch (e) {
          console.log(e);
        }
        entry = input2.getNextEntry();
        continue;
      }
      let output: File = new File(data, name);
      out.setFilePath(output.getPath());
      IOUtils.copyStream(input2, out);
      out.close();
      out = null;
      entry = input2.getNextEntry();
    }
    if (input2 != null) {
      input2.close();
    }
    input1.close();
  }
```
### deflate 压缩功能
指定文件夹路径压缩deflate文件夹。
``` javascript
import { DeflateFile } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  DeflateFileTest(): void {
    try{
      var data = globalThis.context.filesDir
        console.info('directory obtained. Data:' + data);
        DeflateFile(data + '/hello.txt', data + '/hello.txt.deflate')
          .then((isSuccess) => {
            if (isSuccess) {
              AlertDialog.show({ title: '压缩成功',
                message: '请查看手机路径 ' + data + '/test.txt.deflate',
                confirm: { value: 'OK', action: () => {
                  this.isDeCompressGZipShow = true
                } }
              })
            }
          });
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### deflate 解压功能
指定文件夹路径解压deflate文件夹。
``` javascript
import { InflateFile } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
InflateFileTest(): void {
    try{
      var data = globalThis.context.filesDir
        InflateFile(data + "/hello.txt.deflate", data + '/test.txt')
          .then(() => {
            AlertDialog.show({ title: '解缩成功',
              message: '请查看手机路径 ' + data + '/test.txt',
              confirm: { value: 'OK', action: () => {
              } }
            })
          });
    }catch(error){
      console.error('File to obtain the file directory. Cause: ' + error.message);
    }
  }
```
### cpio 压缩功能
指定文件夹路径压缩cpio文件夹。
``` javascript
import {File, InputStream, OutputStream, ArchiveStreamFactory, ArchiveOutputStream, CpioArchiveEntry, IOUtils } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
  jsCpioTest(): void {
    try{
        this.testReadLongNamesBSD(globalThis.context.filesDir)
      }catch(error){
        console.error('File to obtain the file directory. Cause: ' + error.message);
      }
  }
  testReadLongNamesBSD(data: string): void {
    let output: File = new File(data, this.newFolder + ".cpio");
    let file1: File = new File(data + '/' + this.newFolder, "test1.xml");
    let inputStream1 = new InputStream();
    inputStream1.setFilePath(file1.getPath());
    let out: OutputStream = new OutputStream();
    out.setFilePath(output.getPath());
    let os: ArchiveOutputStream = ArchiveStreamFactory.DEFAULT.createArchiveOutputStream("cpio", out);
    let archiveEntry1: CpioArchiveEntry = new CpioArchiveEntry();
    archiveEntry1.initCpioArchiveEntryNameSize("test1.xml", Long.fromNumber(file1.length()));
    os.putArchiveEntry(archiveEntry1);
    IOUtils.copyStream(inputStream1, os);
    os.closeArchiveEntry();
    os.close();
    out.close();
    AlertDialog.show({ title: '压缩成功',
      message: '请查看手机路径 ' + data + '/',
      confirm: { value: 'OK', action: () => {
        this.isDeCompressGArShow = true
      } }
    })
  }
```
### cpio 解压功能
指定文件夹路径解压cpio文件夹。
``` javascript
import {File, InputStream, OutputStream, CpioArchiveInputStream, CpioArchiveEntry, CpioConstants } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
jsUnCpioTest(): void {
try{
        this.testUnCompressCpio(globalThis.context.filesDir)
      }catch(error){
        console.error('File to obtain the file directory. Cause: ' + error.message);
      }
}
  testUnCompressCpio(data: string) {
    let input: File = new File(data, this.newFolder + '.cpio');
    let input1: InputStream = new InputStream();
    input1.setFilePath(input.getPath());
    let tais = new CpioArchiveInputStream(input1, CpioConstants.BLOCK_SIZE, CharacterSetECI.ASCII.getName());
    let cpioArchiveEntry: CpioArchiveEntry = null;
    while ((cpioArchiveEntry = tais.getNextCPIOEntry()) != null) {
      let name: string = cpioArchiveEntry.getName();
      let tarFile: File = new File(data + '/' + this.newFolder, name);
      if (name.indexOf('/') != -1) {
        try {
          let splitName: string = name.substring(0, name.lastIndexOf('/'));
          fileio.mkdirSync(data + '/' + this.newFolder + '/' + splitName);
        } catch (err) {
        }
      }
      let fos: OutputStream = null;
      try {
        fos = new OutputStream();
        fos.setFilePath(tarFile.getPath())
        let read: number = -1;
        let buffer: Int8Array = new Int8Array(1024);
        while ((read = tais.readBytes(buffer)) != -1) {
          fos.writeBytesOffset(buffer, 0, read);
        }
      } catch (e) {
        throw e;
      } finally {
        fos.close();
      }
    }
    AlertDialog.show({ title: '解压成功',
      message: '请查看手机路径' + data + '/' + this.newFolder + '/test1.xml',
      confirm: { value: 'OK', action: () => {
        this.isCompressGArFileShow = true
      } }
    })
  }
```
## 目录
```
/commons-compress # 三方库源代码
├── src      # 框架代码
│   └── main
│   	└── ets
│   		└── components
│       		└── archivers
│           		├── ar  	# ar源代码存放目录
│           		├── cpio   	# cpio源代码存放目录
│           		├── dump  	# dump源代码存放目录
│           		├── lzma    # lzma源代码存放目录
│           		├── tar   	# tar源代码存放目录
│           		└── zip     # zip源代码存放目录
│       		└── compressors
│           		├── brotli  # brotli源代码存放目录
│           		├── bzip2   # bzip2源代码存放目录
│           		├── lz77support  # lz77support源代码存放目录
│           		├── lzw     # lzw源代码存放目录
│           		├── snappy  # snappy源代码存放目录
│           		└── xz     	# xz源代码存放目录
│           		└── z    	# z源代码存放目录
│       		└── deflate     # deflate源代码存放目录
│       		└── gzip  # gzip源代码存放目录
│       		└── lz4   # lz4源代码存放目录
│       		└── util  # 工具源代码存放目录
│       		└── zip   # zip源代码存放目录
│       		└── zstd  # zstd源代码存放目录0
```
## 接口说明
| **接口**                                                     | 参数                                                         | 功能                                           |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------------------------------------- |
| createArchiveOutputStream(archiverName: string, out: OutputStream) | archiverName:存档名称
out:存档输出流                   | 创建存档输出流。                               |
| zipCompress(path: string, dest: string)                      | path:文件路径
dest:生成后的文件名称                    | zip压缩方法。                                  |
| zipDeCompress(path: string, target?: string)                 | path:解压后的文件路径和名称
target:解压后的路径        | zip解压方法。                                  |
| gzipFile(src: string, dest: string)                          | src:文件路径
dest:生成后的文件名称                     | gzip压缩方法。                                 |
| unGzipFile(src: string, target: string)                      | path:解压后的文件路径和名称
target:解压后的路径        | gzip解压方法。                                 |
| createCompressorOutputStream(name: string, out: OutputStream) | name:压缩器名称
out:输出流                             | 从存档程序名称和输出流创建存档输出流。         |
| createCompressorInputStream(  name: string,  inputStream: InputStream, actualDecompressConcatenated: boolean) | name:压缩器名称
inputStream:输入流
actualDecompressConcatenated:解压级 | 从存档程序名称和输入流创建存档输入流。         |
| copy(input: InputStream, output: OutputStream)               | input:输入流
output:输出流                             | 将输入流的内容复制到输出流中。                 |
| setFilePath(path: string)                                    | path:指定路径                                               | 打开指定文件路径。                             |
| createCompressorInputStream2(name: string, inputStream: InputStream) | name:压缩器名称
inputStream:输入流                     | 从压缩器名称和输入创建压缩器输入流。           |
| readFully(input: InputStream, array: Int8Array)              | input:输入流
array:需要填充数组                        | 从输入中读取尽可能多的信息,以填充给定的数组。 |
| maxCompressedLength(uncompressedSize: number)                | uncompressedSize:解压的大小                                 | 读取压缩长度                                   |
| getZstdFrameCompress(input: Int8Array, inputOffset: number, inputLength: number, output: Int8Array, outputOffset: number, maxOutputLength: number) | input:输入流
inputOffset:输入偏移量
inputLength:输入长度
output:输出流
outputOffset:输出偏移量
maxOutputLength:最大输出长度 | 获取压缩数据流。                               |
| decompress(input: Int8Array, inputOffset: number, inputLength: number, output: Int8Array, outputOffset: number, maxOutputLength: number) | input:输入流
inputOffset:输入偏移量
inputLength:输入长度
output:输出流
outputOffset:输出偏移量
maxOutputLength:最大输出长度 | 获取解压数据流。                               |
| lz4Compressed(src: string, dest: string)                     | src:文件路径
dest:生成后的文件名称                     | 压缩为lz4文件。                                |
| lz4Decompressed(src: string, target: string)                 | path:解压后的文件路径和名称
target:解压后的路径        | 解压lz4文件。                                  |
| createArchiveOutputStreamLittle(archiverName: string, out: OutputStream) | archiverName:存档名称
out:输出流                       | 创建存档输出流。                               |
| createArchiveInputStream(  archiverName: string,  inputStream: InputStream,  actualEncoding: string) | archiverName:存档名称
inputStream:输入流
actualEncoding:条目编码 | 从存档程序名称和输入流创建存档输入流。         |
| snappyCompress(path, newfile)                                | path:文件路径
newfile:生成后的文件名称                 | 压缩为sz文件。                                 |
| snappyUncompress(path, newfolder, newfile, newfile1)         | path:文件路径
newfolder: 文件名称
newfile:生成后的文件名称
newfile1:文件名称 | 解压sz文件。                                   |
| DeflateFile(src: string, dest: string)                       | src:文件路径
dest:生成后的文件名称                     | 压缩为deflate文件。                            |
| InflateFile(src: string, target: string)                     | src:解压后的文件路径和名称
target:解压后的路径         | 解压deflate文件。                              |
## 兼容性
支持 OpenHarmony API version 8 及以上版本。
## 开源协议
本项目基于 [Apache License 2.0](https://gitee.com/openharmony-tpc/CommonsCompress/blob/master/LICENSE) ,请自由地享受和参与开源。
## 贡献代码
使用过程中发现任何问题都可以提 [Issue](https://gitee.com/openharmony-tpc/CommonsCompress/issues) 给我们,当然,我们也非常欢迎你给我们发 [PR](https://gitee.com/openharmony-tpc/CommonsCompress/pulls) 。