简体   繁体   中英

FileWriter is not writing anything into the file

I programmed a little game that also has a highscore being displayed when the game is over.

The highscore is saved into a integer variable simply called highscore .

Now I am trying to safe the highscore into a file to avoid it being reset everytime you close the app.

My approach was using a FileWriter as you can see below. The game is still running smoothly and everything is fine I don't get any errors etc. but it does not safe anything into the file.

I just don't understand why.

Thankful for any help.

 private void saveHighscore() {
        File highscoreFile = new File("C:\\Users\\FuadM\\Desktop\\Mueckenfang\\Highscore.txt");
        try (FileWriter highscoreWriter = new FileWriter(highscoreFile)) {

            if (!highscoreFile.exists()) {
                highscoreFile.createNewFile();
            }
            highscoreWriter.write("" + highscore);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

EDIT: I just checked and I am getting this message in the terminal:

    W/System.err: java.io.FileNotFoundException: 
    C:\Users\FuadM\Desktop\Mueckenfang\Highscore.txt: open failed: EROFS
    (Read- only file system)

Android doesn't have a C: drive, or a desktop, or a Mueckenfang directory. I'm not quite sure what your thought process was, but your phone is certainly not going to be capable of writing files on your PC's desktop.

You can write to files on Android, but that's not what you should be doing here. Android apps ship with SQLite (a simple database system) built in, and that's where a game should be storing a high score. I think your next step should be to search the web for a tutorial on how to do SQLite from Android.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM