9 Star 1 Fork 12

OpenHarmony-TPC / CommonsCompressEts

加入 Gitee
与超过 800 万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README.md

commons-compress

简介

commons-compress组件定义了一个用于处理压缩和存档格式的 API,包含bzip2、gzip、lzma、xz、Snappy、LZ4、Brotli、DEFLATE、Zstandard 和 ar、cpio、tar、zip、dump、7z等格式的压缩/解压功能。

compp.gif

下载

  npm install @ohos/commons-compress --save

OpenHarmony npm环境配置等更多内容,请参照 如何安装OpenHarmony npm包

使用说明

zip 压缩功能

指定文件夹路径压缩zip文件夹。

import {zipCompress} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

jsZipTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      zipCompress(data + '/' + this.newFolder, data + '/' + this.newFolder + '.zip').then((isSuccess) => {
        if (isSuccess) {
          AlertDialog.show({ title: '压缩成功',
            message: '请查看手机路径 ' + data + '/',
            confirm: { value: 'OK', action: () => {
              this.isDeCompressGZipShow = true
            } }
          })
        }
      })
    })
  }

zip 解压功能

指定文件夹路径解压zip文件夹。

import {zipDeCompress} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

unJsZipTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      zipDeCompress(data + '/' + this.newFolder + '.zip')
        .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文件夹。

import {gzipFile} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

gzipFileTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      console.info('directory obtained. Data:' + data);
      gzipFile(data + '/cache_images/hello.txt', data + '/cache_files/test.txt.gz')
        .then((isSuccess) => {
        if (isSuccess) {
          AlertDialog.show({ title: '压缩成功',
            message: '请查看手机路径 ' + data + '/cache_files/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文件夹。

import {unGzipFile} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

unGzipFileTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      unGzipFile(data + '/cache_files/test.txt.gz', data + '/cache_images/test.txt')
        .then((isSuccess) => {
        if (isSuccess) {
          AlertDialog.show({ title: '解缩成功',
            message: '请查看手机路径 ' + data + '/cache_images/test.txt',
            confirm: { value: 'OK', action: () => {
            } }
          })
        }
      });
    })
      .catch((error) => {
      console.error('File to obtain the file directory. Cause: ' + error.message);
    })
  }

xz 压缩功能

指定文件夹路径压缩XZ文件夹。

import {File, OutputStream,InputStream,IOUtils,CompressorStreamFactory,CompressorOutputStream} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

testXZCreation(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      console.info('directory obtained. Data:' + data);
      let input = new File(data, "/cache_files/hello.txt");
      let output = new File(data, "/cache_files/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.copy(input1, cos);
      cos.close();
      input1.close()
      AlertDialog.show({ title: '压缩成功',
        message: '请查看手机路径 ' + data + '/cache_files/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文件夹。

import {File, OutputStream,InputStream,IOUtils,CompressorStreamFactory,CompressorInputStream} from '@ohos/commons-compress' 
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

unXZFileTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      let input = new File(data, "/cache_files/hello.txt.xz");
      let output = new File(data, "/cache_files/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).createCompressorInputStream2("xz", input1)
      IOUtils.copy(inputs, out);
      out.close();
      input1.close();
      AlertDialog.show({ title: '解缩成功',
        message: '请查看手机路径 ' + data + '/cache_files/hello1.txt',
        confirm: { value: 'OK', action: () => {
        } }
      })
    })
      .catch((error) => {
      console.error('File to obtain the file directory. Cause: ' + error.message);
    })
  }

Z 解压功能

指定文件夹路径解压Z文件夹。

import {File, OutputStream,InputStream,IOUtils,CompressorInputStream,CompressorStreamFactory} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

unZFileTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
        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).createCompressorInputStream2("z", inputStream);
        IOUtils.copy(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 文件夹。

import {ZstdCompressor, IOUtils,InputStream,OutputStream,File,ZstdDecompressor,System} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

	compressedSize: number = 0;
  	compressed: Int8Array;
  	original: Int8Array;

//zstd压缩功能
testZstdCompressed(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      console.info('directory obtained. Data:' + data);
      let compressor = new ZstdCompressor();
      let output = new File(data, "/cache_files/hello.txt.zst");
      let input = new File(data, "/cache_files/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.readFully(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 + '/cache_files/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() {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      console.info('directory obtained. Data:' + data);
      let time = System.currentTimeMillis()
      let compressor = new ZstdDecompressor();

      let output = new File(data, "/cache_files/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()
      let time1 = System.currentTimeMillis()
      console.log('consoleconsoleconsole1: ' + (time1 - time) );

      AlertDialog.show({ title: '解压成功',
        message: '请查看手机路径 ' + data + '/cache_files/newhello.txt',
        confirm: { value: 'OK', action: () => {
          this.isDeCompressBzip2Show = true
        } }
      })
    })
      .catch((error) => {
      console.error('File to obtain the file directory. Cause: ' + error.message);
    })
  }

ar 压缩功能

指定文件夹路径压缩ar文件夹。

import { ArchiveEntry, ArchiveUtils, ArArchiveInputStream, ArArchiveEntry, ArchiveStreamFactory, ArchiveOutputStream, InputStream, File,OutputStream,IOUtils} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

jsArTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
        this.testArArchiveCreation(data)
      })
  }

 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.copy(input1, os);
    os.closeArchiveEntry();
    os.close();
    AlertDialog.show({ title: '压缩成功',
      message: '请查看手机路径 ' + data + '/',
      confirm: { value: 'OK', action: () => {
        this.isDeCompressGArShow = true
      } }
    })
  }

ar 解压功能

指定文件夹路径解压ar文件夹。

import { ArchiveEntry, ArchiveUtils, ArArchiveInputStream, ArArchiveEntry, ArchiveStreamFactory, ArchiveOutputStream, InputStream, File,OutputStream,IOUtils} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

jsUnArTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
        this.testReadLongNamesBSD(data)
      })
  }

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文件夹。

import { CompressorInputStream,CompressorStreamFactory,ArchiveInputStream,ArchiveStreamFactory,ArchiveEntry,InputStream,File,OutputStream,IOUtils} from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import ability_featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';
 
brotilTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
        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().createCompressorInputStream2("br", input1)
        IOUtils.copy(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);
      })
  }

bzip2 压缩功能

指定文件夹路径压缩bzip2文件夹。

import { CompressorInputStream,CompressorStreamFactory,InputStream,OutputStream,IOUtils,CompressorOutputStream} from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import ability_featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';

bzip2FileTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
        console.info('directory obtained. Data:' + data);
        let inputStream: InputStream = new InputStream();
        inputStream.setFilePath(data + '/cache_images/hello.txt');
        let fOut: OutputStream = new OutputStream();
        fOut.setFilePath(data + '/cache_files/hello.txt.bz2');
        let cos: CompressorOutputStream = new CompressorStreamFactory(false).createCompressorOutputStream("bzip2", fOut);
        IOUtils.copy(inputStream, cos);
        cos.close();
        inputStream.close();
        AlertDialog.show({ title: '压缩成功',
          message: '请查看手机路径 ' + data + '/cache_files/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文件夹。

import { CompressorInputStream,CompressorStreamFactory,InputStream,OutputStream,IOUtils,CompressorOutputStream} from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';

unBzip2FileTest(): void {
    var context = featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
        let inputStream: InputStream = new InputStream();
        inputStream.setFilePath(data + '/cache_files/hello.txt.bz2');
        let fOut: OutputStream = new OutputStream();
        fOut.setFilePath(data + '/cache_files/hello.txt');
        let input:CompressorInputStream = new CompressorStreamFactory(false).createCompressorInputStream2("bzip2", inputStream);
        IOUtils.copy(input, fOut);
        inputStream.close();
        fOut.close();
        AlertDialog.show({ title: '解缩成功',
          message: '请查看手机路径 ' + data + '/cache_files/hello.txt',
          confirm: { value: 'OK', action: () => {
          } }
        })
      })
      .catch((error) => {
        console.error('File to obtain the file directory. Cause: ' + error.message);
      })
  }

lz4 压缩功能

指定文件夹路径压缩lz4文件夹。

 import {lz4Compressed} from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

  lz4CompressedTest(): void {
    var context = ability_featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      lz4Compressed(data + '/cache_images/test.txt', data + '/cache_files/test.txt.lz4')
      AlertDialog.show({ title: '压缩成功',
        message: '请查看手机路径 ' + data + '/cache_files/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文件夹。

import {lz4Decompressed} from '@ohos/commons-compress'  
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';
lz4DecompressedTest(): void {
    var context = ability_featureAbility.getContext();
    context.getFilesDir()
      .then((data) => {
      lz4Decompressed(data + '/cache_files/test.txt.lz4', data + '/test.txt')
      AlertDialog.show({ title: '解缩成功',
        message: '请查看手机路径 ' + data + '/test.txt',
        confirm: { value: 'OK', action: () => {
        } }
      })
    })
      .catch((error) => {
      console.error('File to obtain the file directory. Cause: ' + error.message);
    })
  }

lzma,sevenz7 压缩功能

指定文件夹路径压缩lzma,sevenz7文件夹。

  import {Decoder, Encoder,InputStream,OutputStream,Exception,System } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

  encoder(path) {
    let inputStream: InputStream = new InputStream();
    let outputStream: OutputStream = new OutputStream();
    outputStream.setFilePath(path + '/test.xml.lzma')
    //outputStream.setFilePath(path + '/test.xml.7z')
    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文件夹。

import {Decoder, Encoder,InputStream,OutputStream,Exception,System } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

decoder(path) {
    let decoder: Decoder = new Decoder();
    let inputStream: InputStream = new InputStream();
    inputStream.setFilePath(path + '/test.xml.lzma')
    //inputStream.setFilePath(path + '/test.xml.7z')
    let outputStream: OutputStream = new OutputStream();
    outputStream.setFilePath(path + '/cache_files/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文件夹。

import { File, InputStream, OutputStream, ArchiveStreamFactory, TarArchiveEntry, IOUtils } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

jsTarTest(): void {
   var context = featureAbility.getContext();
   context.getFilesDir()
      .then((data) => {
        this.testArArchiveCreation(data);
      })
}

testArArchiveCreation(data:string) {
   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.createArchiveOutputStreamLittle("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.copy(input1, os);
   os.closeArchiveEntry();
   os.close();
}

tar 解压功能

指定文件夹路径解压tar文件夹。

import { File, InputStream, OutputStream, TarArchiveInputStream, TarConstants, TarArchiveEntry } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

jsUnTarTest(): void {
   var context = featureAbility.getContext();
   context.getFilesDir()
      .then((data) => {
         this.testUnCompressTar(data);
      })
}
  
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);
         }
      } catch (e) {
        throw e;
      } finally {
        fos.close();
      }
   }
}

snappy 压缩功能

指定文件夹路径解压sz文件夹。

import { snappyCompress } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

  @State newfolder: string = 'newfolder'
  @State newfile: string = 'bla.txt'
  @State newfile1: string = 'bla1.txt'

snappyJsTest(value) {
   var context = ability_featureAbility.getContext();
   context.getFilesDir()
      .then((data) => {
          let path = data + '/' + this.newfolder
          snappyCompress(path, this.newfile)
      })
}

snappy 解压功能

指定文件夹路径解压sz文件夹。

import { snappyUncompress } from '@ohos/commons-compress'
import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility';

  @State newfolder: string = 'newfolder'
  @State newfile: string = 'bla.txt'
  @State newfile1: string = 'bla1.txt'

snappyJsTest() {
   var context = ability_featureAbility.getContext();
   context.getFilesDir()
   .then((data) => {
       snappyUncompress(data, this.newfolder, this.newfile, this.newfile1)
    })
}

dump 解压功能

指定文件夹路径解压dump文件夹。

import { File, InputStream, OutputStream, ArchiveStreamFactory, ArchiveInputStream, ArchiveEntry, IOUtils } from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import ability_featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';

jsDumpTest(): void {
   var context = featureAbility.getContext();
   context.getFilesDir()
   .then((data) => {
     this.testDumpUnarchiveAll(data,'dump/bla.dump')
   })
}

testDumpUnarchiveAll(data:string ,archive: string):void {
   let file1: File = new File(data, archive);
   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.copy(input2, out);
      out.close();
      out = null;
      entry = input2.getNextEntry();
   }
   if (input2 != null) {
     input2.close();
   }
   input1.close();
}

deflate 压缩功能

指定文件夹路径压缩deflate文件夹。

import { DeflateFile } from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';

DeflateFileTest(): void {
   var context = featureAbility.getContext();
   context.getFilesDir()
   .then((data) => {
     DeflateFile(data + '/hello.txt', data + '/hello.txt.deflate')
   })
}

deflate 解压功能

指定文件夹路径解压deflate文件夹。

import { InflateFile } from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';

InflateFileTest(): void {
  var context = featureAbility.getContext();
  context.getFilesDir()
    .then((data) => {
      InflateFile(data + "/hello.txt.deflate",data + '/test.txt') 
    })        
}

cpio 压缩功能

指定文件夹路径压缩cpio文件夹。

import {File, InputStream, OutputStream, ArchiveStreamFactory, ArchiveOutputStream, CpioArchiveEntry, IOUtils } from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';

jsCpioTest(): void {
 var context = featureAbility.getContext();
 context.getFilesDir()
   .then((data) => {
     this.testReadLongNamesBSD(data)
   })
}

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.createArchiveOutputStreamLittle("cpio", out);


 let archiveEntry1: CpioArchiveEntry = new CpioArchiveEntry();
 archiveEntry1.initCpioArchiveEntryNameSize("test1.xml", Long.fromNumber(file1.length()));
 os.putArchiveEntry(archiveEntry1);
 IOUtils.copy(inputStream1, os);
 os.closeArchiveEntry();

 os.close();
 out.close();
}

cpio 解压功能

指定文件夹路径解压cpio文件夹。

import {File, InputStream, OutputStream, CpioArchiveInputStream, CpioArchiveEntry, CpioConstants } from '@ohos/commons-compress'
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';

jsUnCpioTest(): void {
 var context = featureAbility.getContext();
 context.getFilesDir()
   .then((data) => {
     this.testUnCompressCpio(data)
   })
}

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();
   }
 }
}

目录

/commons-compress # 三方库源代码
├── src      # 框架代码
│   └── main
│   	└── MainAbility
│   		└── 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) 创建存档输出流。
zipCompress(path: string, dest: string) zip压缩方法。
zipDeCompress(path: string, target?: string) zip解压方法。
gzipFile(src: string, dest: string) gzip压缩方法。
unGzipFile(src: string, target: string) gzip解压方法。
createCompressorOutputStream(name: string, out: OutputStream) 从存档程序名称和输出流创建存档输出流。
createCompressorInputStream( name: string, inputStream: InputStream, actualDecompressConcatenated: boolean) 从存档程序名称和输入流创建存档输入流。
copy(input: InputStream, output: OutputStream) 将输入流的内容复制到输出流中。
setFilePath(path: string) 打开指定文件路径。
createCompressorInputStream2(name: string, inputStream: InputStream) 从压缩器名称和输入创建压缩器输入流。
readFully(input: InputStream, array: Int8Array) 从输入中读取尽可能多的信息,以填充给定的数组。
maxCompressedLength(uncompressedSize: number) 读取压缩长度
getZstdFrameCompress(input: Int8Array, inputOffset: number, inputLength: number, output: Int8Array, outputOffset: number, maxOutputLength: number) 获取压缩数据流。
decompress(input: Int8Array, inputOffset: number, inputLength: number, output: Int8Array, outputOffset: number, maxOutputLength: number) 获取解压数据流。
lz4Compressed(src: string, dest: string) 压缩为lz4文件。
lz4Decompressed(src: string, target: string) 解压lz4文件。
createArchiveOutputStreamLittle(archiverName: string, out: OutputStream) 创建存档输出流。
createArchiveInputStream( archiverName: string, inputStream: InputStream, actualEncoding: string) 从存档程序名称和输入流创建存档输入流。
snappyCompress(path, newfile) 压缩为sz文件。
snappyUncompress(path, newfolder, newfile, newfile1) 解压sz文件。
DeflateFile(src: string, dest: string) 压缩为deflate文件。
InflateFile(src: string, target: string) 解压deflate文件。

兼容性

支持 OpenHarmony API version 8 及以上版本。

开源协议

本项目基于 Apache License 2.0 ,请自由地享受和参与开源。

贡献代码

使用过程中发现任何问题都可以提 Issue 给我们,当然,我们也非常欢迎你给我们发 PR

仓库评论 ( 0 )

你可以在登录后,发表评论

简介

暂无描述 展开 收起
TypeScript 等 2 种语言
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/openharmony-tpc/CommonsCompressEts.git
git@gitee.com:openharmony-tpc/CommonsCompressEts.git
openharmony-tpc
CommonsCompressEts
CommonsCompressEts
master

搜索帮助

120539 77c3c0f1 1850385 100910 489c739c 1850385