我目前正在将消息从我的应用程序中的多个活动类保存到单个文件中。每个活动类都有相同的函数 WriteToFile。
public void WriteToFile(String info) {
FileOutputStream FoutS = null;
OutputStreamWriter outSW = null;
try {
FoutS = openFileOutput("file.txt", MODE_PRIVATE);
outSW = new OutputStreamWriter(FoutS);
outSW.write(info);
outSW.flush();
}
catch (Exception e) {
}
finally {
try {
outSW.close();
FoutS.close();
} catch (IOException e) {
}
}
}
我一直在尝试创建一个单独的类,该类将这个函数写入(和读取)到文件,但我无法不出错。
我认为该函数需要将上下文传递给 WriteToFile void,例如...
//Changes to this line
public void WriteToFile(String info, Context context) {
FileOutputStream FoutS = null;
OutputStreamWriter outSW = null;
try {
//Changes to this line
FoutS = context.openFileOutput("file.txt", MODE_PRIVATE);
outSW = new OutputStreamWriter(FoutS);
outSW.write(info);
outSW.flush();
}
catch (Exception e) {
}
finally {
try {
outSW.close();
FoutS.close();
} catch (IOException e) {
}
}
}
如果这是正确的,我是否正确地传递了上下文?
String msg = "This is a message";
WriteToFile(msg, this);
它不起作用,所以我做错了什么。