Hi am working on a game which saves several states once my save button is cliked, such as: name, totalScore ...
This is how I saved it:
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);
}
I want to load a game instead of starting a new one every time. I can read the data from a text file and print it to screen, but don't know how to load these into the labels (e.g. for name) to begin the game. Any ideas?
My code for loading the text file so far is:
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();
}
I call this method at a "load" button click. Any ideas would be greatly appreciated.
答案 0 :(得分:2)
执行此操作的常用方法是使用java.util.Properties
从文本文件中读取键值对。在这个完整的example中,属性文件用于初始化AlphaComposite
规则的词汇表。 JComboBox
中显示enum
条规则。test.cpp
。您还可以使用属性初始化java.util.prefs.Preferences
实例中的默认值,如引用的游戏here中所示。
答案 1 :(得分:1)
将单个保存文件读入工作内存不需要ArrayList
。既然你写了编写文件的方法,你就会隐含地知道哪些数据在哪里,所以如果你的写函数看起来像(这是一种伪代码,但它得到了重点)
outFile.writeLine(foo.name)
outFile.writeLine(foo.health)
outFile.writeLine(foo.level)
使用foo
作为角色类实例的名称。您的阅读功能看起来像
bar.name = inFile.getLine()
bar.health = inFile.getLine()
bar.level = inFile.getLine()
当然,您需要首先将bar
构建为班级的空实例,并执行所有相关的fileIO设置和清理工作,并且不要忘记从bar
返回你的阅读功能。
答案 2 :(得分:0)
Loop through each line using readLine() and save them to an ArrayList. Since you're the one who created the text file, you know what should be in each line when you retrieve the values from the array.
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);
}