I am currently saving a message to a single file from multiple activity classes within my app. Each activity class has the same function 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) {
}
}
}
I have been attempting to create a separate class which holds this function write (and read) to file but I haven't been able to without getting errors.
I think the function needs to have context passed through to the WriteToFile void like...
//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) {
}
}
}
if that is correct am I passing the context correctly?
String msg = "This is a message";
WriteToFile(msg, this);
It's not working so I am doing something wrong.
You should use your context to call the method
context.openFileOutput("file.txt", context.MODE_PRIVATE);
what you wrote has no meaning, or far from what you mean.