我的目标是从电话本地存储〜/下载中打开CSV文件并将其导入数据库。
我正在使用Flutter,到目前为止,我查看了许多示例,但没有成功。
但是我能够在控制台中打印文件的内容,但是为此,我必须在app项目中的assets / res文件夹中有一个文件。
如果使用getExternalStorageDirectory,结果将得到仿真/存储/ 0 /。如何进入设备的内部存储(不是外部存储,因为手机无法选择SD卡,否则将无法使用)。
对于数据库,我可以使用sqflite来获得一个有效的示例,但由于我是个菜鸟,所以无法在已经设计好的应用程序中使用它。
答案 0 :(得分:1)
使用package:open_file / open_file.dart中的open_file将文件作为文本文档打开,然后自行解析内容。
答案 1 :(得分:0)
回到开始,但离我需要的解决方案有点远。我有file_picker(https://pub.dartlang.org/packages/file_picker),它有助于使用文件资源管理器选择文件:
String _filePath;
void getFilePath() async {
try {
String filePath = await FilePicker.getFilePath(
type: FileType.CUSTOM, fileExtension: 'csv');
if (filePath == '') {
return;
}
print("Path: " + filePath);
setState(() {
this._filePath = filePath;
});
} on PlatformException catch (e) {
print("Error picking file: " + e.toString());
}
}
使用上述代码返回文件的路径,例如“ /storage/emulated/0/Download/1.csv”。
现在,我使用此路径读取文件的内容:
...
RaisedButton(
child: const Text('Import data - dummy'),
color: Theme.of(context).accentColor,
elevation: 4.0,
splashColor: Colors.blueGrey,
onPressed: () {
print('Verifying click done');
// Show contents of the file
readContents();
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: getFilePath,
tooltip: 'Choose file to import',
child: new Icon(Icons.sd_storage),
)
...
Future<File> get _localFile async {
final path = await _filePath;
return File('$path');
}
Future<int> readContents() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If we encounter an error, return 0
return 0;
}
}
现在,由于上述代码应返回CSV文件的内容,因此它什么也不做。 CSV文件包含项目列表。
有人可以让我知道为什么并且如此友好地向我展示如何将文件的解析内容保存为一个字符串,或者甚至更好的字符串,这些字符串代表文件中的每一列吗?
谢谢!