Flutter 压缩和解压缩

Eva*_*ana 8 flutter flutter-dependencies

你好,我想问一下如何在flutter中压缩和解压缩成字符串:

例子 :

final int BUFFER_SIZE = 40;
    ByteArrayInputStream is = new ByteArrayInputStream(compressed);
    GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
    StringBuilder string = new StringBuilder();
    byte[] data = new byte[BUFFER_SIZE];
    int bytesRead;
    while ((bytesRead = gis.read(data)) != -1) { string.append(new String(data, 0, bytesRead)); }
    gis.close();
    is.close();
    return string.toString();
Run Code Online (Sandbox Code Playgroud)

Oma*_*att 4

您可以使用存档插件来压缩和解压缩文件。

解压缩:

// Read the Zip file from disk.
final bytes = File('test.zip').readAsBytesSync();

// Decode the Zip file
final archive = ZipDecoder().decodeBytes(bytes);

// Extract the contents of the Zip archive to disk.
for (final file in archive) {
  final filename = file.name;
  if (file.isFile) {
    final data = file.content as List<int>;
    File('out/' + filename)
      ..createSync(recursive: true)
      ..writeAsBytesSync(data);
  } else {
    Directory('out/' + filename).create(recursive: true);
  }
}
Run Code Online (Sandbox Code Playgroud)

要创建 zip 文件:

// Zip a directory to out.zip using the zipDirectory convenience method
var encoder = ZipFileEncoder();
encoder.zipDirectory(Directory('out'), filename: 'out.zip');
Run Code Online (Sandbox Code Playgroud)