这可能是一个愚蠢的问题,但我正在创建一个从文件中获取数据以结帐的功能。我试图在此函数中使用缓冲读取器和文件读取器,尽管bufferredReader.readLine()始终返回null。也没有logcat。我需要一些帮助。有两种方法,一种保存到文件,另一种从文件中检索数据。我已经知道数据正确地传递到保存到文件函数。
以下是保存到文件功能:
public boolean saveToBill(Editable user, Editable points, Editable mows) {
String FILENAME = "/billDrafts";
String string = user + "," + points + "," + mows;
try {
FileWriter writer = new FileWriter(this.getFilesDir() + FILENAME);
writer.write(string);
Toast toast = Toast.makeText(this, "Saved to checkout. Click the 3 dots, then checkout to complete billing process." + string, Toast.LENGTH_LONG);
toast.show();
return true;
} catch (Exception e) {
Toast toast = Toast.makeText(this, "Failed to save file for checkout.", Toast.LENGTH_LONG);
toast.show();
return false;
}
}
以下是从文件中读取的功能:
public void checkout() {
String FILENAME = this.getFilesDir() + "/billDrafts";
try {
FileReader fileReader = new FileReader(FILENAME);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String bills = bufferedReader.readLine();
Toast toast = Toast.makeText(this, "Checkout Complete" + bills, Toast.LENGTH_LONG);
toast.show();
bufferedReader.close();
fileReader.close();
} catch (FileNotFoundException fileNotFoundException) {
Toast toast = Toast.makeText(this, "Checkout Failed. Make sure you have somebody to bill.", Toast.LENGTH_LONG);
toast.show();
} catch (IOException ioException) {
Toast toast = Toast.makeText(this, "Checkout Failed. An unknown error occurred during checkout.", Toast.LENGTH_LONG);
toast.show();
}
}
答案 0 :(得分:0)
看来你的saveToBill
并没有真正将数据写入文件。您需要在编写器上调用flush()
或close()
才能将缓冲的数据传递到实际文件中。
由于您不同时使用它们,因此您的文件为空,因此readLine()
返回null。
flush()
和close()
之间略有不同,您可以阅读它们