我正在尝试编写一个 Java 应用程序,但为了使其正常工作,我需要检查它是否是第一次打开该应用程序。有什么方法可以在 Mac 上执行此操作,以便如果这是第一次打开应用程序,那么它会执行特定操作?
最佳答案
按照描述使用 java.util.prefs.Preferences here 。我还尝试了谷歌,这是第一个弹出的东西。我们先使用 Google。
编辑:
这是一个带注释的文件,用于显示步骤。
定义一个键,您可以每次使用一个字符串,最好不要用于执行目的以及重构。该键稍后将用于访问首选项。
创建 Preferences 类的实例。
定义一个节点,我喜欢的一个好选择是使用类简单名称而不是字符串。该节点将保存首选项,这样,如果您在不同节点中具有类似键的不同首选项,则不会发生冲突。
使用 get[Type]([KEY], [default_value]) 访问它并使用 set[Type]([KEY], [value]) 设置它,如下所示。
您可以运行此应用程序两次以查看差异。
package com.company;
import java.util.prefs.Preferences;
public class Main {
// This key will be used to access the preference, could literally have any name and value
private static final String SOME_KEY = "some_key";
private Preferences preferences;
public Main(){
// Defining a new node for saving preference. Analogoues to a location.
preferences = Preferences.userRoot().node(this.getClass().getSimpleName());
}
public boolean firstRun(){
// See what is save in under SOME_KEY, if nothing found return true, if something found, return that.
return preferences.getBoolean(SOME_KEY, true);
}
public void run(){
// Put the value of false in the preference with the key SOME_KEY
preferences.putBoolean(SOME_KEY, false);
}
public static void main(String[] args) {
Main main = new Main();
System.out.println("Is this the frist time running this app?");
System.out.println(main.firstRun());
main.run();
}
}
关于Java:如何检查java应用程序之前是否在mac上运行过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677783/