我目前正在學習 Dart,我遇到了一些與檔案讀/寫相關的問題。
我有一個藍牙傳感器向我發送資料(非常快),在對其應用一些處理方法后,我想將其寫入檔案中。我剛剛意識到,雖然我從藍牙接收了我需要的所有資料,但我并沒有將它們全部寫入檔案。
我有兩個檔案:一個用于讀取資料并對其進行一些處理,另一個用于處理檔案操作。
// 1:讀取資料并應用處理
var dataList = [];
Tuple2<String, List<List<double>>> dataParser(List<int> dataFromDevice) {
... // Some processing to obtain data
dataList.add(data);
if(dataList.isNotEmpty) FileStorage().writeFile();
}
我可以看到我收到的所有資料都寫在 dataList 中。
// 2:檔案操作
class FileStorage{
Future<String?> get _localPath async {
final currentDirectory = await getApplicationDocumentsDirectory();
return currentDirectory.path;
}
Future<File> get _localFile async {
final currentPath = await _localPath;
return File('$currentPath/A_B.bin');
}
Future writeFile() async {
final file = await _localFile;
await file.writeAsBytes(dataList[0], mode: FileMode.append).whenComplete(() => dataList.removeAt(0)
}
}
問題實際上發生在 writeFile() 函式中。它正在寫入一些資料,但例如,如果它必須寫入 [1, 2, 3, 4, 5],它正在寫入 [1, 4, ...]。
我嘗試使用其他一些技術但失敗了。請問我有什么困難可以做到這一點嗎?
非常感謝。
uj5u.com熱心網友回復:
我在處理 1 天后發現了問題...我確定問題發生在 中writeFile,因為我checked dataList[0]和它包含我想要的內容。
顯然,這await _localFile是“獲取目錄路徑,創建新檔案等”的時間。這是我浪費時間和丟失資料的那一刻。
相反,我現在_localFile在資料采集的一開始就呼叫它,而不是每次都呼叫它writeFile。這是合乎邏輯的,雖然我不認為await會落后我的程式這么多。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/430405.html
上一篇:HTMLPHP檔案上傳::上傳的檔案沒有出現在服務器上
下一篇:如何將網頁保存為擴展名
