Reputation: 3968
Hallo,
Here's some code which writes a data class to a file, then checks to see that the file exists. I can see that the file exists on the emulator, but file.exists() and therefore saveStateAvailable() returns false.
private void saveStateFile() {
/*DEBUG*/Log.d(this.getClass().getName(), "saveStateFile: Started");
mGameData = getGameData();
try {
FileOutputStream fileoutputstream = openFileOutput(mGameData.pilotName + STATE_FILE_EXTENSION, Context.MODE_WORLD_WRITEABLE);
ObjectOutputStream objectoutputstream;
objectoutputstream = new ObjectOutputStream(fileoutputstream);
objectoutputstream.writeObject(mGameData);
objectoutputstream.close();
fileoutputstream.close();
/*DEBUG*/Log.i(this.getClass().getName(), "saveStateFile: State saved to "+mGameData.pilotName + STATE_FILE_EXTENSION);
} catch (IOException e) {
/*DEBUG*/Log.e(this.getClass().getName(), "saveStateFile: Error writing data state file, "+mGameData.pilotName + STATE_FILE_EXTENSION);
e.printStackTrace();
}
/*DEBUG*/Log.d(this.getClass().getName(), "saveStateFile: Finished stateFileAvailable="+stateFileAvailable());
}
private boolean stateFileAvailable() {
File file = new File(mGameData.pilotName + STATE_FILE_EXTENSION);
/*DEBUG*/Log.d(this.getClass().getName(), "stateFileAvailable: Called ("+mGameData.pilotName + STATE_FILE_EXTENSION+" exists = "+file.exists()+")");
return file.exists();
}
Any ideas?
-Frink
Upvotes: 3
Views: 4971
Reputation: 41972
You need to use Context#getFileStreamPath(String)
where the String
is the filename of the File
object you are trying to access. Then you can call File#exists
on that object. So:
File file = getFileStreamPath(mGameData.pilotName + STATE_FILE_EXTENSION);
Gives you access to the File
object that points to the correct place in your private app storage area.
What your code is going atm is accessing the file /<your file name>
which is on the root path. You file obviously does not exist there.
Upvotes: 5