Java 读取/写入用于保存的txt文件

Java 读取/写入用于保存的txt文件,java,file,save,lwjgl,slick2d,Java,File,Save,Lwjgl,Slick2d,我现在已经在gameover将高分写入文本文件,并在游戏加载时读取它们。我现在遇到的问题是,由于我没有创建txt文件highscores.txt,所以在任何地方都找不到它。是否可以在找不到文件时创建该文件?以下是相关代码: 将高分写入gameover的文件: if(gameOver == true){ sbg.enterState(5, new FadeOutTransition(), new FadeInTransition()); if(score >

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

将高分写入gameover的文件:

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;
    }
我知道如果不存在这样的文件,我可以创建它:

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("------------------------------------");
}

但我不知道如何使用缓冲区。请帮忙

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

让我先说一句,我不熟悉在文件系统中存储游戏相关信息的最佳实践。话虽如此,听起来你在开发这个软件的过程中正在努力学习,所以考虑到这一点,我建议从编写一个简单的.txt文件开始

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

如何创建和写入txt文件:
如何读取txt文件:
和Java教程,以获得最佳效果:

我要做的是:
1。确定何时要触发写入。
您希望何时更新高分文件?在我看来,这可能是在158年左右的游戏类中,在那里你确定游戏已经结束:

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

2。找出何时需要读取文件以填充高分。在pastebin中查看您的代码,在我看来,在开始加载游戏状态/循环之前,您应该在Blop类的主方法中启动时执行以下操作:

        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文件,直到您对它有了更多的了解

需要记住的几件事:

  • 您将遇到许多异常处理。在中读取该文件时,您需要确定游戏是否因无法加载高分文件而无法启动?另一方面,当您无法写入该文件时,这是一个严重错误吗?
  • 编辑:
    关于后续问题,您希望使用正在使用的文件的实际名称。关于你的第二个问题,请看一些。这是一个很好的介绍。

    一切正常,下面是如何在游戏结束时保存高分,以及如何在程序启动时加载高分

    当程序第一次启动时,它会检查是否有名为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文件:

    最后,当您关闭程序时,highscore1、highscore2和highscore3的最后值被写入highscores.txt文件中。所以当你启动程序时,你想从文件中读取那些整数。由于文件包含字符串,我需要整数,因此我必须以字符串的形式从文件中获取行,将其转换为整数,然后将其分配给变量Highscores.HighScores1。。。 (位于“文件检查器”if()语句下)


    因此,当您再次打开程序时,highscores.txt文件中写入的最后一个值将被放入您的highscores整数中。你就是这样救他们的

    我忘了提到有一个Highscores类,它包含Highscores 1、Highscores 2和Highscores 3整数,供所有其他类使用。你能同时添加Highscores类吗?是的,当然没有粘贴箱,请。相关代码必须在问题本身中。简单地删除所有不相关的代码-当按下按钮回答这个问题时,你所做的事情与此无关。对不起,伙计们,这里的first timer:“)好的,我不确定如何向你展示我所做的,但我已经编写了文件,但我不确定在程序加载时如何读取它。你能解释一下吗?非常感谢你的回答!所以在看了这个之后,我注意到这个“”是否意味着我用“highscores.txt”替换它?""? ...最后一个问题,如果文件还不在目录中,有没有办法创建它?我知道java文件有一种方法:if(!file.exists()){…但我不确定是否可以将其应用于缓冲区。
    //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();
        }
    
    //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();
            }
    
    //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();