Android and ObjectOutputStream to resource file

2019-07-31 06:57发布

I'm really new to android development, and my first project was a simple game wich 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 implemetation.

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 wich 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?

2条回答
Deceive 欺骗
2楼-- · 2019-07-31 07:26

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

查看更多
太酷不给撩
3楼-- · 2019-07-31 07:43

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!

查看更多
登录 后发表回答