首页 > 解决方案 > FileSystemException:无法打开文件,路径 = 'assets/busStops.txt'(操作系统错误:没有这样的文件或目录,errno = 2)

问题描述

我似乎无法加载存储在资产中的 txt 文件。每当我尝试访问它时,都会出现以下错误:

FileSystemException: Cannot open file, path = 'assets/busStops.txt' (OS Error: No such file or directory, errno = 2)

我也将该文件添加到我的 pubspec 文件中:

  assets:
    - assets/BusSD.png
    - assets/SubtractBD.png
    - assets/VectorDD.png
    - assets/busRoutes.txt
    - assets/busStops.txt

这是我访问文件的代码


class FileUtilsBusStopInfo {
  static Future<String> get getFilePath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  static Future<File> get getFile async {
    //final path = await getFilePath;

    return File('assets/busStops.txt');
  }

  static Future<File> saveToFile(String data) async {
    final file = await getFile;
    return file.writeAsString(data);
  }

  static Future<String> readFromFile() async {
    try {
      final file = await getFile;
      String fileContents = await file.readAsString();

      print(fileContents);
      return fileContents;
    } catch (e) {
      print(e);
      print('returning blank');
      return "";
    }
  }
}

图像加载正常。我可以做些什么来解决这个问题?先感谢您!

标签: androidflutterdart

解决方案


尝试通过以下方式加载文件:

import 'package:flutter/services.dart' show rootBundle;

// Method
final data = rootBundle.load('assets/busStops.txt');
// ...

Flutter 中的资产由其服务加载,而不是从设备的文件系统加载。


推荐阅读