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

Viewed 4192

I'm trying to download *.xlsx file using dio.download, and it's throwing the errors: Unhandled Exception: FileSystemException: Cannot open file, path = '/storage/emulated/0/Android/data/com.example.foodagator_app/files/file.xlsx' (OS Error: No such file or directory, errno = 2)

Another one error from try/catch block: FileSystemException: Creation failed, path = 'File: '' (OS Error: Read-only file system, errno = 30)

I wrote the permission in androidmanifest for external storage, and also tried temporary directory, but it's not working. Can anyone help me with this? Here is my code

void download() async {
    var tempDir = await getExternalStorageDirectory();
    File file = File(tempDir!.path + '/file.xlsx');
    try {
      Response response = await dio.download(
        url,
        file,
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
        ),
      );

      var raf = file.openSync(mode: FileMode.write);
      // response.data is List<int> type
      raf.writeFromSync(response.data);
      await raf.close();
    } catch (e) {
      print('Error is: $e');
    }
  }

  void readFile() async {
    var tempDir = await getExternalStorageDirectory();

    var filePath = tempDir!.path + "/file.xlsx";
    var bytes = File(filePath).readAsBytesSync();
    var decoder = SpreadsheetDecoder.decodeBytes(bytes, update: true);
    for (var table in decoder.tables.keys) {
      print(table);
      print(decoder.tables[table]!.maxCols);
      print(decoder.tables[table]!.maxRows);
      for (var row in decoder.tables[table]!.rows) {
        print('$row');
      }
    }
  }
4 Answers

This error is getting because there is no file named file.xlsx you can check if file exists or not

if(file.existsSync())

if file does not exist, you can create one using,

new File('$path/file.xlsx').create(recursive: true);

Sorry, I had problem with await usage - I tried to get access to file before I downloaded it

in android 11 and higher use bewlow permission , without tools:ignore="ScopedStorage"

   <uses-permission 
  android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

In my case, it was caused because I had moved a dart file to another folder but my other files were still referencing that file using the old path, you can import the file again using the new path and using the "package:" keyword to solve this error.

Moral: Don't use relative paths to import a file anywhere in your project, always use the "package:" scheme.

Related