我希望在android中保存/加载一个非常简单的应用程序。 我们的想法是检查onCreate()方法中是否存在文件,以及是否加载了onCreate中的设置。 这是正确的功能吗? 保存在onPause()函数中完成。
我将这样做的方法是通过FileOutputStream和FileInputStream。
但是我的代码看起来如何呢? 目前我有这个:
if (new File(FILENAME).isFile()) {
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
fis.read();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
numOfEpisode = Integer.parseInt(fis.toString());
numOfSeason = Integer.parseInt(fis.toString());
}
忽略我尚未处理异常的事实,因为我知道测试时文件会存在。
protected void onPause() {
try {
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(numOfEpisode);
fos.write(numOfSeason);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
当我关闭应用程序时(当调用onPause()时),应用程序当前给我一个错误。 任何人都可以指向我的任何方向吗?
另外,我如何知道FileOutputStream.write()以什么方式编写我的语句?这是FIFO还是LIFO?
答案 0 :(得分:2)
我会使用SharedPreferences,因为它更容易做,并且专门用于存储和检索设备中的少量信息。查看How to use SharedPreferences in Android to store, fetch and edit values以了解如何完成此操作。
您可以阅读onCreate中的值并存储它们。当你onPause时,你会把它们写到SharedPreferences。
答案 1 :(得分:0)
尝试使用此代码:
File Gdir = new File(Environment.getExternalStorageDirectory()
.getPath() + "/NewFolder/");
// have the object build the directory structure, if needed.
if (!Gdir.exists()) {
Gdir.mkdirs();
}
File outputFile = new File(Gdir, "file.txt");
// now attach the OutputStream to the file object, instead of a
// String representation
try {
FileWriter mod = new FileWriter(
outputFile);
mod.write(numOfEpisode);
mod.write(numOfSeason);
mod.flush();
mod.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "File saved in: "+outputFile, Toast.LENGTH_LONG).show();