我有一个 android 应用程序正在将值写入该应用程序还创建的文件。我能够写入文件,然后再次从文件中读取。但是,一旦该活动完成,文件似乎现在已经消失了,或者丢失了它的值。
我知道你不能通过资源管理器浏览文件,除非你 root 手机和/或以特定用户身份运行 adb 服务器。
这是我写入文件的代码: public void savePrices(View view) { FileOutputStream outputStream;
File getFilesDir = this.getFilesDir();
File filePathOne = new File(getFilesDir, filename);
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
for (int i = 0; i < priceArray.length; i++) {
outputStream.write(String.format("%.2f\n", priceArray[i]).getBytes());
}
Toast.makeText(this, "Prices saved successfully!", Toast.LENGTH_SHORT).show();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
这是我读取文件的代码:
public void loadPrices(View view) {
int i = 0;
final InputStream file;
BufferedReader reader;
try{
file = getAssets().open(filename);
reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();
while(line != null){
line = reader.readLine();
priceArray[i] = Double.parseDouble(line);
i++;
}
} catch(IOException ioe){
ioe.printStackTrace();
hamburgerPriceText.setText(String.format("%.2f", priceArray[0]));
hotDogPriceText.setText(String.format("%.2f", priceArray[1]));
chipsPriceText.setText(String.format("%.2f", priceArray[2]));
beerPriceText.setText(String.format("%.2f", priceArray[3]));
popPriceText.setText(String.format("%.2f", priceArray[4]));
Toast.makeText(this, "Prices loaded successfully!", Toast.LENGTH_SHORT).show();
}catch (NumberFormatException e) {
Log.e("Load File", "Could not parse file data: " + e.toString());
}
}
在调用设置数组中的值并将值保存到文件中的 save 方法后,我运行一个 clear 方法来删除活动字段和数组中的所有值。因此,当我运行 read 方法并填充活动上的字段时,我知道这些值来自读取文件。这是我知道我正在成功保存和读取文件的唯一方法。
我的问题是如何使其永久化?如果我关闭保存值的活动,然后立即运行 read 方法,所有值都是 0。
有什么我想念的吗?如何写入文件,以便在活动关闭或应用程序完全关闭时,我仍然可以保留这些值?