gpt4 book ai didi

java - 如何保存最后一个 session 的变量值(程序退出)

转载 作者:行者123 更新时间:2023-12-02 01:02:08 24 4
gpt4 key购买 nike

如何在程序中保存变量的值,然后在下一个程序运行时重用它?我不想通过文件写入/读取来完成此操作。

最佳答案

使用Java Preferences API .

import java.util.prefs.*;

public class Example {
// Preference key
private static final String FRUIT = "fruit";

public void savePreference(String favoriteFruit) {
Preferences prefs = Preferences.userNodeForPackage(Example.class);

prefs.put(FRUIT, favoriteFruit);
}

public String readPreference() {
Preferences prefs = Preferences.userNodeForPackage(Example.class);

return prefs.get(FRUIT, "default");
}
}

数据是根据类的完全限定名称存储的,因此您的包名称和类名称是相关的。来自 documentation for the Preferences class :

This class allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. Typical implementations include flat files, OS-specific registries, directory servers and SQL databases. The user of this class needn't be concerned with details of the backing store.

关于java - 如何保存最后一个 session 的变量值(程序退出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57760642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com