【发布时间】:2011-09-25 03:59:03
【问题描述】:
好吧,我在各种 Android 和场外文档/帮助网站中阅读了很多关于保存和访问实现的信息,但我仍然无法理解实现以及它是如何工作的,所以我最后的手段是转向 StackOverFlow(我自己在做这个)
我有时会在这个问题上听起来有点愚蠢和迟钝,因为我在申请的同时也在学习,所以请耐心等待(我已经标记了整个文档的部分内容我有问题的地方):
首先,我看到要实现保存的文件,必须编写(取自 android 文档):
//Declarations
String FILENAME = "hello_file";
String string = "hello world!";
//Meaning that FILENAME is to be saved as hello_file, and "hello world!" converts the string to bytes
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
在其中保存数据的任何函数(例如按钮)中,如下所示:
public void testButtonPressToSave() {
FileOutputStream testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE);
testSaveFile.write();
testSaveFile.close();
}
但是,当我在代码中实现它时,Eclipse 建议我在 openFileOutput 部分使用 try/catch 异常,整个事情变为:
public void testButtonPressToSave() {
FileOutputStream testSaveFile;
try {
testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
testSaveFile.write(testString.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
testSaveFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
(问题)这正常吗?如果它在另一个活动中,我如何能够重复使用我保存的文件?我是否将整个主要活动导入到一个小部件提供程序类中?
另外,我完全理解:
1) FileOutputStream testSaveFile; and testSaveFile = openFileOutput(SavedFile, Context.MODE_PRIVATE);
将 testSaveFile 声明为 FileOutputStream 对象,并使用 Context.MODE_PRIVATE 保存文件(.txt?),这将文件限制为只能由应用程序本身访问。
和,
2) testSaveFile.close();
以某种方式结束流(但这很直接,它只是关闭文件)
我不太明白的部分是,如何在 SavedFile 数据包中保存多个变量?
Android 文档在 FileOutputStream 下为我提供了可用的 write() 函数:
public void write (byte[] buffer, int offset, int byteCount)
public void write (byte[] buffer)
public void write (int oneByte)
这不是我想要的,因为我需要流来保存多个变量,例如 String 和 Integer[]。
(问题)如何将所需的数据类型保存到 SavedFile 中?
我还阅读了有关序列化的信息,但我不确定将文件保存到我的应用程序中的实际工作原理。另外,我不太相信序列化在 Dalvik VM (Android) 上会非常有效,因为我阅读和经历的大部分代码都是基于 Java 系统的。
还有一个我不理解的 Bundle android 资源,但似乎是将各种多个变量存储到一个包中然后在下一个活动中解包它们的答案,尽管我不明白我是如何能够做到的实际将其保存到文件或其他东西中。
好吧,我说了很多点,但如果有人能够回答这些问题,我将不胜感激。您不必提供答案,但非常感谢您提供清晰的解释(尤其是围绕技术术语:S)
【问题讨论】: