未处理的异常:FileSystemException: Cannot open file, path ..(OS Err



我正在尝试使用dio下载*.xlsx文件。下载,它抛出错误:未处理异常:FileSystemException: Cannot open file, path = '/storage/emululated/0/Android/data/com.example.foodagator_app/files/file.xlsx' (OS Error: No such file or directory, errno = 2)

try/catch块中的另一个错误:FileSystemException: Creation failed, path = 'File: " (OS Error: Read-only File system, errno = 30)

我在androidmanifest中为外部存储写了权限,并且还尝试了临时目录,但它不起作用。有人能帮我一下吗?这是我的代码

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

由于没有名为file.xlsx的文件,因此出现此错误你可以检查文件是否存在

if(file.existsSync())

如果文件不存在,可以使用

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

android 11及以上版本未经允许使用,不含tools:ignore="ScopedStorage"

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

在我的例子中,这是因为我已经移动了一个dart文件到另一个文件夹,但我的其他文件仍然使用旧路径引用该文件,您可以使用新路径再次导入该文件,并使用"包:"关键字来解决这个错误。

寓意:不要在项目的任何地方使用相对路径导入文件,总是使用"package:"计划。

使用

final directory = await getApplicationDocumentsDirectory();
await Hive.initFlutter(directory.path);

当然,你需要

import 'package:path_provider/path_provider.dart';
WidgetsFlutterBinding.ensureInitialized();    
final directory = await getApplicationDocumentsDirectory();
Hive.init(directory.path);

您也可以自定义名称

String createDownloadDocName(){
return'${fileName}-${DateTime.now().microsecond}';
}

最新更新