且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将游戏结果保存到文本文件

更新时间:2023-02-02 21:36:15

我为您创建了一个基础类,该基础类会将胜利保存到文本文件中并从文本文件中检索出来.

I've created a basic class for you that will save the wins to a text file and retrieve them from a text file.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class WinsFileManager {

    String path = System.getProperty("user.home").replace("\\", "\\\\") + "\\";

    public int getWins(String fileName) {

        String fullPath = path + fileName;
        int wins = 0;

        try {
            wins = Integer.parseInt(new Scanner(new File(fullPath)).nextLine());
        } catch (NumberFormatException e) {} 
          catch (FileNotFoundException e) {
            wins = 0;
        }

        return wins;
    }

    public void saveWins(String fileName, int wins) {
        PrintWriter out = null;

        try {
            out = new PrintWriter(path + fileName, "UTF-8");
            out.println(wins);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这是在不同位置使用上述类的对象的方式.

Here's how you'd use an object of the above class from a different location.

public class test {

    public static void main(String[] args) {
        WinsFileManager manager = new WinsFileManager();
        String fileName = "O Wins.txt";

        manager.saveWins(fileName, 5);
        System.out.println(manager.getWins(fileName));
    }
}

以上示例中的控制台输出为"5".

The console output in the above example would be '5'.

我已经完成了困难的部分.现在由您决定将其实现到程序中.首先,每当有人获胜时,我都将通过getWins方法检索存储的获胜次数,将该值加一,然后使用saveWins方法来存储递增的值.请记住,即使退出程序,胜利值也会被保存.

I've done the hard part. Now it's up to you to implement this into your program. To start off, whenever someone wins, I would retrieve the stored number of wins via the getWins method, add one to that value, and then use the saveWins method to store the incremented value. Keep in mind that even once you exit your program, the win values will be saved.

注意:如果您要做的就是跟踪程序寿命内的获胜情况,则有许多简便的方法.

Note: There are much easier ways to do this if all you want to do is keep track of the wins within the lifespan of the program.