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?
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!
You can't write to your resources directory. You should probably write to internal storage instead. The doc on data storage should be helpful.