flutterarchive

Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/res.zip' (OS Error: No such file or directory, errno = 2)


I'm trying to extract files from an archive but I'm getting this error.

E/flutter (31571): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/res.zip' (OS Error: No such file or directory, errno = 2)

My code. https://pub.dev/packages/archive/example

final bytes = File('assets/res.zip').readAsBytesSync();
final archive = ZipDecoder()
    .decodeBytes(bytes, verify: true, password: '123');

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

pubspec.yaml

 assets:
    - assets/
    - assets/res.zip

Solution

  • You need to get the asset first from the bundled binary. For this, use the rootBundle.

    The rootBundle contains the resources that were packaged with the application when it was built. To add resources to the [rootBundle] for your application, add them to the assets subsection of the flutter section of your application's pubspec.yaml manifest.

    Here's an example:

    final byteData = await rootBundle.load('assets/res.zip');
    final buffer = byteData.buffer;
    final archive = ZipDecoder()
        .decodeBytes(buffer.asUint8List(), verify: true, password: '123');
    
    // ...
    

    Another approach could be extracting the asset to a temp folder like the following:

    final byteData = await rootBundle.load('assets/res.zip');
    final buffer = byteData.buffer;
    File file = await File('/path/to/extract/res.zip').writeAsBytes(
        buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
    final bytes = File('/path/to/extract/res.zip').readAsBytesSync();
    final archive =
        ZipDecoder().decodeBytes(bytes, verify: true, password: '123');
    
    // ...
    

    To get the /path/to/extract/ path, for example the temp folder, use the plugin path_provider and the function getTemporaryDirectory.

    Path to the temporary directory on the device that is not backed up and is suitable for storing caches of downloaded files.