我的Activity类中有代码来加载和保存文件。它工作正常。代码保存了cFavretClass的内容。我正在尝试清理代码,因此我将文件i / o移动到cFavret类中。
我无法获得编译代码。现在我收到错误openFileOutput is undefined in type cFavrets
。
我假设这个方法是在Googles Activity Class中声明的? 这是否意味着所有文件I / O必须在活动类中?
boolean Save()
{
String FILENAME = "hello_file";
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE );
fos.write(buffer);
fos.close();
}
// just catch all exceptions and return false
catch (Throwable t) {
return false;
}
return true;
}
boolean Load()
{
String FILENAME = "hello_file";
try {
FileInputStream fos = openFileInput(FILENAME);
buffer[0]=0;
fos.read(buffer);
fos.close();
}
// just catch all exceptions and return false
catch (Throwable t) {
// maybe file does not exist, try creating it
return false;
}
return true;
}
答案 0 :(得分:1)
这是否意味着所有文件I / O必须在活动类中?
不,但是有问题的方法是从上下文中调用的 - 只需将上下文传递给此cFavretClass
的构造函数(如果您愿意,也可以传递给方法本身):
Context mContext;
public cFavretClass(Context context) {
mContext = context;
}
...
// in your methods:
mContext.openFileOutput(FILENAME);
答案 1 :(得分:0)
正如JRaymond所解释的那样,openFileOutput
是Context
的一种方法,Activity
来自{{1}}。这种方法很特殊,因为它允许您为应用程序创建私有文件。
您也可以使用普通的Java I / O类来写入外部存储(SD卡),但每个人都可以读取这些文件。