Android file.exists () not working

Hello,

Here is some code that writes a data class to a file, then checks if the file exists. I see that the file exists in 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

+3
source share
1 answer

You need to use Context#getFileStreamPath(String), where Stringis the file name of the object Fileyou are trying to access. Then you can call File#existson this object. So:

File file = getFileStreamPath(mGameData.pilotName + STATE_FILE_EXTENSION);

Gives you access to an object Filethat points to the right place in your personal application storage area.

atm - /<your file name>, . , , .

+5

Source: https://habr.com/ru/post/1785543/


All Articles