I am working on android studio and I would like to write/store a file in internal storage. I know there are a couple of questions like this on stack overflow. I've managed to get this code from those.
public static void writeObj(Alarm alarm, Context context){
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try{
fos = new FileOutputStream("ArrayList.txt", true);
oos = new ObjectOutputStream(fos);
oos.writeObject(alarm);
oos.flush();
oos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This code was not working for me. I managed to figure out I was getting a FileNotFound exception because the FileOutputStream could not create my file. So I did some more digging and added this above my try/catch (replacing "ArrayList.txt" with f in FileOpenOutputStream).
File f = new File(context.getFilesDir(),"ArrayList.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
This created the file for me, getting me past the FileNotFound exception catch, but now I'm getting an IOException. I haven't been able to find a solution to this problem. Could someone give me some tips as to the reason why I would be getting this exception. Is there maybe some type of permission I need to add to the Manifest file that I don't know about?
Refer to documentation here - https://developer.android.com/reference/java/io/ObjectOutputStream
Only objects that support the java.io.Serializable interface can be written to streams.
So you must implement Serializable interface for Alarm class and all of its fields must also be Serializable in order to use ObjectOutputStream.
You can find more info from documentation.
Additional references
Serialization Java: which classes need to "implement Serializable"?