尝试从文件加载数字时获取随机数



编辑:我正在尝试创建一个"点击器"游戏,从数据文件中加载最后记录的数字。

我正在开发一个简单的一键式游戏,这是一个点击游戏。没有什么花哨的,只是一个JButton和一个JLabel.我是Java IO类的新手,所以我不知道是什么原因导致这种情况发生。我没有收到任何错误,但是一个随机数,除了每次都相同的数字。

写入方法:

public static void write(long data) {
File file = new File("data.txt");
path = file.getAbsolutePath();
try {
PrintWriter writer = new PrintWriter(file);
writer.println(data);
writer.close();
} catch (IOException e) {
System.out.println(e);
}
}

读取方法:

public static long read() {
long data = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(path));
data = reader.read();
reader.close();
return data;
} catch (IOException e) {
System.err.format("Exception occurred trying to read '%s'.", path);
e.printStackTrace();
return 0;
}
}

图形用户界面:

public static void gui() {
. . .
// Declarations {
JFrame frame = new JFrame("Clicker");
JPanel panel = new JPanel();
JButton clickerButton = new JButton("Click");
JLabel amountOfClicks = new JLabel("Click to get started!");
// }
. . .
// * * * * * * * * * * *
panel.setLayout(new GridLayout(2, 0));
// Action {
clickerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
if (read() >= 1) {
clickerCount = read() + 1;
amountOfClicks.setText("You have clicked: " + clickerCount + " times.");
write(clickerCount);
} else {
clickerCount = clickerCount + 1;
amountOfClicks.setText("You have clicked: " + clickerCount + " times.");
write(clickerCount);
}
}
});
// }
. . .

还有我得到的随机数 (48(,当我单击按钮时,它应该增加 1。但是现在由于它从"48"开始,第一次点击:增加 1。第二: 4. 第三: 1. 然后停止增加。我想写入文件的原因是,我可以加载最后记录的数字。

Properties文件中检索数据:

存储数据

首先创建一个Properties对象并向其中添加数据。你可以认为它的行为类似于Map。每个键都有一个存储的关联值。不幸的是,对于您的情况,Properties只存储字符串,但我们可以解决这个问题:

Properties props = new Properties();
props.setProperty("SomeKey", "SomeValue"); // String => String
props.setProperty("AnotherKey", String.valueOf(123456L)); // String => String (Long)

当然,123456L可以用长整型(或任何其他基元类型(的变量替换。对于非基元,您可以使用.toString().(非基元见底部注释(

要将数据写入文件,您需要一个FileOutputStream

FileOutputStream output = new FileOutputStream("config.properties");

然后写入该文件:

props.store(output, null);

如果您打开该文件,它是纯文本,您将看到如下所示的内容:

#Sun Jul 16 22:47:45 EST 2017
SomeKey=SomeValue
AnotherKey=123456

读取数据

读取数据正好相反,现在我们需要一个FileInputStream,我们将调用.load().

FileInputStream input = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(input);

现在最后一部分是访问数据,请记住所有内容都是字符串。

String someKey = props.getProperty("SomeKey");
long anotherKey = Long.valueOf(props.getProperty("AnotherKey"));

仅此而已。


您可以使用Long.parseLong(props.getProperty("AnotherKey"))而不是.valueOf()

对于非原语,这很可能不是要走的路,因为所有内容都保存为字符串。对于非基元,请查看Serializable