【问题标题】:Read/write txt file for saves读取/写入 txt 文件以进行保存
【发布时间】:2015-10-22 21:14:01
【问题描述】:

我现在在游戏结束时将高分写入文本文件,并在游戏加载时读取它们。我现在遇到的问题是 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("------------------------------------");
}

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

【问题讨论】:

  • 我忘了提到有一个 Highscores 类,它包含 highscore1、highscore2 和 highscore3 整数,供所有其他类取用。
  • 你也可以添加高分类吗?
  • 是的,当然pastebin.com/4BKjdxfc
  • 请不要粘贴。相关代码必须在问题本身中。只需删除所有不相关的代码 - 当为这个问题按下按钮时,你所做的并不真正相关。
  • 对不起各位,第一次来这里:')

标签: java file save lwjgl slick2d


【解决方案1】:

让我先说我不熟悉在文件系统上存储游戏相关信息的最佳实践。话虽这么说,听起来您在开发它时正在尝试学习,因此考虑到这一点,我建议从写入一个简单的 .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。弄清楚何时要触发写入。
您希望何时更新您的高分文件?对我来说,这看起来像是在 ln 158 左右的 Gameplay 类中,您确定游戏已经结束:

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


2.弄清楚何时需要读取文件以填充高分。在 pastebin 中查看您的代码,在我看来,在您开始加载游戏状态/循环之前,您希望在 Blop 类的 main 方法中启动时执行此操作:

        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.弄清楚如何格式化文本文件。您已经订购了分数,因此您也可以以这种方式存储它们。每行保存一个分数或使用分隔符,如“,”或“|”可以使用你目前拥有的东西。


从简单的文本文件开始,如果适合您的需要,可以更改为其他文件。如果这是一个测试/学习项目,我强烈建议您保持简单并坚持使用简单的 .txt 文件,直到您进一步了解它为止

需要注意的几点:

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

编辑: 关于您的后续问题,您想使用您正在使用的文件的实际名称。 Javadocs are your friend。关于您的第二个问题,请查看other SO posts。覆盖得很好。

【讨论】:

  • 非常感谢您的回答!所以在查看了这个stackoverflow.com/questions/731365/… 之后,我注意到这个“”是否意味着我将它替换为“highscores.txt”? “”? ...
  • 最后一个问题,如果文件不在目录中,有没有办法创建文件?我知道有一个用于 java Files: if(!file.exists()){ ... 但我不确定我是否可以将它应用于缓冲区。
【解决方案2】:

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

【讨论】:

  • 好的,我不确定如何向您展示我所做的事情,但是我已经编写了文件,但是我不确定在程序加载时如何读取它。你能解释一下吗?
【解决方案3】:

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

当程序第一次启动时,它会检查是否有一个名为 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();
    }

当您玩几次游戏时,当游戏处于“游戏结束”状态时,高分将写入 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 ... (这是在“文件检查器” 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 文件中的最后一个值将被放入您的高分整数中。这就是你拯救他们的方式!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多