Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

You can't write to your resources directory. You should probably write to internal storage instead. The doc on data storage should be helpful.

Solution 2:

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:

Stringfilename="res/raw/testfile.txt";
try
{
    Filefile=newFile(filename);
    if (!file.exists()) {
        if (!file.createNewFile()) {
           thrownewIOException("Unable to create file");
        }
    // else { //prompt user to confirm overwrite }FileOutputStreamfileout=newFileOutputStream(file);
    ObjectOutputStreamout=newObjectOutputStream(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!

Post a Comment for "Android And Objectoutputstream To Resource File"