将资产从包复制到文件系统
Copy asset from bundle to file system
我正在尝试将 sqlite 数据库从根包复制到文件系统以便使用它。
我尝试了很多不同的方法,但最终总是将不正确的数据量写入磁盘。我使用的代码如下所示:
Directory appDocDir = await getExternalStorageDirectory();
String path = join(appDocDir.path, "data.db");
bool exists = await new File(path).exists();
if (!exists) {
var out = new File(path).openWrite();
var data = await rootBundle.load("assets/data.sqlite");
var list = data.buffer.asUint8List();
out.write(list);
out.close();
}
您不能写入 Uint8List
to a File
using IOSink.write
的内容(它被设计用于对 String
参数进行操作)。您最终将编写通过在 Uint8List
上调用 toString()
获得的 String
的 UTF-8 编码表示,这可能比列表的实际内容大得多。
相反,您可以使用 IOSink.add
将 Uint8List
写入文件。
在您提供的示例中,您还可以使用 new File(path).writeAsBytes(list)
.
一次写入整个文件
我可以通过以下方式做到这一点。
ByteData data = await rootBundle.load("data.sqlite");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
Directory appDocDir = await getApplicationDocumentsDirectory()
String path = join(appDocDir.path, "data.db");
await File(path).writeAsBytes(bytes);
我正在尝试将 sqlite 数据库从根包复制到文件系统以便使用它。
我尝试了很多不同的方法,但最终总是将不正确的数据量写入磁盘。我使用的代码如下所示:
Directory appDocDir = await getExternalStorageDirectory();
String path = join(appDocDir.path, "data.db");
bool exists = await new File(path).exists();
if (!exists) {
var out = new File(path).openWrite();
var data = await rootBundle.load("assets/data.sqlite");
var list = data.buffer.asUint8List();
out.write(list);
out.close();
}
您不能写入 Uint8List
to a File
using IOSink.write
的内容(它被设计用于对 String
参数进行操作)。您最终将编写通过在 Uint8List
上调用 toString()
获得的 String
的 UTF-8 编码表示,这可能比列表的实际内容大得多。
相反,您可以使用 IOSink.add
将 Uint8List
写入文件。
在您提供的示例中,您还可以使用 new File(path).writeAsBytes(list)
.
我可以通过以下方式做到这一点。
ByteData data = await rootBundle.load("data.sqlite");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
Directory appDocDir = await getApplicationDocumentsDirectory()
String path = join(appDocDir.path, "data.db");
await File(path).writeAsBytes(bytes);