读取数据以从文本文件加载游戏

read data to load game from text file

您好,我正在开发一款游戏,一旦我的保存按钮被点击,它就会保存多个状态,例如:名称、总分...

我是这样保存的:

public static void save()
{
    fileName = new File("Saved Game");

    try
    { 
        fw = new FileWriter(fileName,true);  
    } 
    catch (IOException e)
    {     
        e.printStackTrace();
        JOptionPane.showConfirmDialog(frame, e.toString() + "\nFail to save game.",   
                "Saved", JOptionPane.DEFAULT_OPTION);
    } 

    f = new Formatter(fw); 
    f.format("\n%s\t",level);
    f.format("\t%s\t",  nameLabel.getText());
    f.format("\t%s\t\t", updatedLabel.getText());

    f.close();


    JOptionPane.showConfirmDialog(frame, "Saving was successful.", "Game Saved",   
            JOptionPane.DEFAULT_OPTION);   
}

我想加载一个游戏而不是每次都开始一个新游戏。我可以从文本文件中读取数据并将其打印到屏幕上,但不知道如何将这些加载到标签(例如名称)中以开始游戏。有什么想法吗?

到目前为止我加载文本文件的代码是:

public static void readFromFile (String  fileName) throws IOException
{
    FileReader fr = new FileReader(fileName);
    BufferedReader br = new BufferedReader(fr);

    System.out.println(br.readLine());

    br.close();
}

我在单击 "load" 按钮时调用此方法。任何想法将不胜感激。

使用 readLine() 遍历每一行并将它们保存到 ArrayList。由于您是创建文本文件的人,因此当您从数组中检索值时,您知道每一行中应该包含什么。

BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
        String str;     

List<String> list = new ArrayList<String>();
        while((str = in.readLine()) != null){
            list.add(str);
        }

将单个保存文件读入工作内存不需要ArrayList。因为你写入了写入文件的方法,所以你隐式地知道什么数据在哪里,所以如果你的写入函数看起来像(这有点像伪代码,但它明白了要点)

outFile.writeLine(foo.name)
outFile.writeLine(foo.health)
outFile.writeLine(foo.level)

使用 foo 作为角色实例的名称 class。你的阅读功能看起来像

bar.name = inFile.getLine()
bar.health = inFile.getLine()
bar.level = inFile.getLine()

当然,您首先需要将 bar 构建为 class 的一个空实例,并完成所有相关的文件 IO 设置和清理工作,并且不要忘记 return bar 来自你的阅读功能。

一个常用的方法是使用 java.util.Properties to read key-value pairs from a text file. In this complete example, a property file is used to initialize a glossary of AlphaComposite rules. An enum of the rules is displayed in a JComboBox. You can also use the properties to initialize the default values in an instance of java.util.prefs.Preferences, as shown in the game cited here.