Search code examples
javaandroidresourcesobjectoutputstream

Android and ObjectOutputStream to resource file


I'm really new to Android development, and my first project was a simple game which has a display and a logic part. I would like to add a save feature to the game, but I'm having trouble with the implementation.

I would like to do it this way, with an ObjectOutputStream (just the important part is included)

String filename = "res/raw/testfile.txt";
try
{
    FileOutputStream fileout = new FileOutputStream(filename);
    ObjectOutputStream out = new ObjectOutputStream(fileout);
    out.writeObject(...logic objects...);
} 
catch (Exception ex)
{
    //show the error message
}

But I always get an error message which says, that "no such file ...". Even if I create a "testfile.txt" in the raw directory, it says the same error.

Please help me, what am I doing wrong?


Solution

  • Create a File object with the file name, then check to see if the file exists. If it doesn't, then create the file. If it does, you can just overwrite or prompt the user if they wish to overwrite it. Then pass the File object to your FileOutputStream instead of the filename. Something like this:

    String filename = "res/raw/testfile.txt";
    try
    {
        File file = new File(filename);
        if (!file.exists()) {
            if (!file.createNewFile()) {
               throw new IOException("Unable to create file");
            }
        // else { //prompt user to confirm overwrite }
    
        FileOutputStream fileout = new FileOutputStream(file);
        ObjectOutputStream out = new ObjectOutputStream(fileout);
        out.writeObject(...logic objects...);
    } 
    catch (Exception ex)
    {
        //show the error message
    }
    

    Also make sure you close your outputstreams to prevent any resource leaks.

    Enjoy!