Read/write 用于保存的 txt 文件

Read/write txt file for saves

我现在已经在游戏结束时将高分写入文本文件,并在游戏加载时读取它们。我现在遇到的问题是在任何地方都找不到 txt 文件 highscores.txt,因为我还没有创建它。是否可以在找不到文件时创建文件?这是相关代码:

在游戏结束时将高分写入文件:

if(gameOver == true){
        sbg.enterState(5, new FadeOutTransition(), new FadeInTransition());
        if(score > Highscores.highscore3 && score < Highscores.highscore2){
            Highscores.highscore3 = score;
        }else if(score > Highscores.highscore2 && score < Highscores.highscore1){
            Highscores.highscore3 = Highscores.highscore2;
            Highscores.highscore2 = score;  
        }else if(score > Highscores.highscore1){
            Highscores.highscore3 = Highscores.highscore2;
            Highscores.highscore2 = Highscores.highscore1;
            Highscores.highscore1 = score;
        }else Highscores.highscore1 = score;

        //Write highscores to highscores.txt
        try{
            PrintWriter writer = new PrintWriter("highscores.txt", "UTF-8");
            writer.println(String.valueOf(Highscores.highscore1));
            writer.println(String.valueOf(Highscores.highscore1));
            writer.println(String.valueOf(Highscores.highscore1));
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        gameOver = false;
        gameStart = false;
    }

在程序开始时从 highscores.txt 中读取高分:

public static void main(String[] args) throws IOException{

    BufferedReader in = new BufferedReader(new FileReader("highscores.txt"));
    String line;

    while((line = in.readLine()) != null){
        System.out.println(line);
    }
    in.close();

我知道如果文件不存在我可以创建一个这样的文件:

try{
File save = new File("highscores.txt");
if (!save.exists()){
    save.createNewFile();
System.out.println("\n----------------------------------");
System.out.println("The file has been created.");
System.out.println("------------------------------------");
}

但我不知道如何使用缓冲区来做到这一点。请帮忙!

让文件编写器在程序关闭前将这些值写入 .txt 文件,然后让文件读取器读取并将这些值加载到高分实例变量中。这不是真正的火箭科学。

先声明一下,我不熟悉在文件系统上存储游戏相关信息的最佳做法。话虽这么说,听起来您在开发它时正在尝试学习,因此考虑到这一点,我建议您从写入一个简单的 .txt 文件开始。

实际上已经可以在 SO 上找到基础知识:

如何创建和写入 txt 文件: How do I create a file and write to it in Java?
如何读取txt文件: Reading and displaying data from a .txt file
还有 Java 教程作为很好的衡量标准:https://docs.oracle.com/javase/tutorial/essential/io/file.html

我会做的是:
1。弄清楚何时要触发写入。
您想什么时候更新您的高分文件?对我来说,这看起来会出现在你的游戏 class 大约 ln 158,你确定游戏已经结束的地方:

//Change to GameOverEasy state if gameOver is true
            if(gameOver == true){


2。确定何时需要读入文件以填充 Highscores。在 pastebin 中查看您的代码,对我来说,这似乎是您在开始加载游戏 states/looping:

之前在 Blop class 的主要方法中启动时想要做的事情
        public static void main(String[] args) throws IOException{

            AppGameContainer appgc;
            try{
                    appgc = new AppGameContainer(new Blop(NAME));

                    //Window size
                    appgc.setDisplayMode(960, 640, false);
                    appgc.setShowFPS(false);
                    appgc.setAlwaysRender(true);
                    appgc.setTargetFrameRate(60);
                    appgc.setVSync(true);
                    Display.setIcon(new ByteBuffer[] {
                new ImageIOImageData().imageToByteBuffer(ImageIO.read(new File("res/images/general/Icon16.png")), false, false, null),
                new ImageIOImageData().imageToByteBuffer(ImageIO.read(new File("res/images/general/Icon32.png")), false, false, null)
                });

//TODO: Read in high scores file and populate Highscores class

                    appgc.start();
            }catch(SlickException e){
                    e.printStackTrace();
            }


3。弄清楚如何格式化文本文件。您已经在订购乐谱,因此您也可以那样存储它们。每行保存一个分数或使用“,”或“|”等分隔符将与您目前拥有的一起工作。


从简单的文本文件开始,然后根据需要更改为其他文件。如果这是一个 test/learning 项目,我强烈建议您保持简单并坚持使用一个简单的 .txt 文件,直到您更加了解它

需要记住的几点:

  1. 您将 运行 进行大量异常处理。读入该文件时,您需要确定您的游戏是否因无法加载高分文件而无法启动?另一方面,当您无法写入该文件时,这是一个严重错误吗?
  2. Always be closing

编辑: 关于您的后续问题,您想使用您正在使用的文件的实际名称。 Javadocs are your friend. Regarding your second question, check out some other SO posts。覆盖的很好。

一切正常,这里是如何在游戏结束时保存高分,以及如何在程序启动时加载它们。

当程序第一次启动时,它会检查是否有一个名为 highscores.txt 的文件,如果没有,它会创建一个并在文件中放置 3 个零,这样你就不会得到一个文件为空的异常!:

//Read highscores from highscores.txt
    File save = new File("highscores.txt");
    if (!save.exists()){
        save.createNewFile();
        System.out.println("\n----------------------------------");
        System.out.println("The file has been created.");
        System.out.println("------------------------------------");
        //Places the default 0 values in the file for the high scores
        PrintWriter writer = new PrintWriter("highscores.txt", "UTF-8");
        writer.println(String.valueOf(0));
        writer.println(String.valueOf(0));
        writer.println(String.valueOf(0));
        writer.close();
    }

当你玩几次游戏时,当游戏处于"gameover"状态时,高分将被写入highscores.txt文件:

//Write highscores to highscores.txt
        try{
            PrintWriter writer = new PrintWriter("highscores.txt", "UTF-8");
            writer.println(String.valueOf(Highscores.highscore1));
            writer.println(String.valueOf(Highscores.highscore2));
            writer.println(String.valueOf(Highscores.highscore3));
            writer.close();
        }catch(Exception e){
            e.printStackTrace();
        }

最后,当您关闭程序时,highscore1、highscore2 和 highscore3 的最后值被写入 highscores.txt 文件。因此,当您启动该程序时,您希望从该文件中读取这些整数。由于文件包含字符串,而我想要整数,我必须以字符串的形式从文件中获取行,将其转换为整数,然后将其分配给变量 Highscores.highscore1 ... (这是在 "file checker" if() 语句下)

//Read string values of high score and convert to int to put into variables
    BufferedReader in = new BufferedReader(new FileReader("highscores.txt"));
    String line;
    line = in.readLine();
    Highscores.highscore1 = Integer.parseInt(line);
    line = in.readLine();
    Highscores.highscore2 = Integer.parseInt(line);
    line = in.readLine();
    Highscores.highscore3 = Integer.parseInt(line);

    in.close();

因此,当您再次打开程序时,最后写入 highscores.txt 文件的值将被放入您的高分整数中。这就是您拯救他们的方式!