我最近开始用flutter编程移动的应用程序。我在阅读文件时遇到问题。在实践中,当应用程序运行时,我将一个字符串写入一个文本文件(我也可以正确地读取它)。我的需要是每次访问应用程序时都从这个文件中读取;因此,在initState()函数中,我调用readContent()函数,但得到了以下消息:“FileSystemException:无法打开文件,路径=“/var/mobile/Containers/Data/Application/F8A5A202-45C9-47F6-93C9-E4BAE2AF3C7E/Documents/counter.txt”(OS错误:没有这样的文件或目录,errno = 2)"。你能帮帮我吗?
下面是我的代码:
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
print("directory path: "+directory.path);
return directory.path;
}
Future<io.File> get _localFile async {
final path = await _localPath;
return io.File('$path/counter.txt');
}
String datas = "";
//questa funzione viene richiamata all'avvio della schermata e serve per leggere il valore del flag checkSendingReport dal file
@override
void initState() {
super.initState();
readContent().then((String value) {
print(value);
setState(() {
String data = value;
List data_file_split = data.split("#");
checkSendingReport = data_file_split[1];
check_sending_report = data_file_split[1];
});
});
}
//Questa funzione serve per leggere il file locale scritto in precenza
Future<String> readContent() async {
try {
final file = await _localFile;
// Read the file
String contents = await file.readAsString();
//Returning the contents of the file
return contents;
} catch (e) {
// If encountering an error, return
return 'Error! '+e.toString();
}
}
//questa funzione serve per scrivere il file locale
Future<io.File> writeContent(datetime) async {
final file = await _localFile;
//Setto a true la variabile flag check_sending_report
check_sending_report = true;
//Creo la stringa da inserire nel file: composta da datetime#flag
String data_file = datetime + "#" + check_sending_report.toString();
// Write the file
return file.writeAsString(data_file);
}
字符串
2条答案
按热度按时间plupiseo1#
我猜这个错误是由于最初的文件不存在。因此,您可以添加检查文件是否存在
字符串
如果文件不存在,则可以创建一个。
型
bogh5gae2#
这个答案和我一起完成
字符串