我正在尝试编写Java应用程序,但为了使其正常工作,我需要检查它是否是第一次打开应用程序。有没有办法在Mac上执行此操作,以便如果它是第一次打开应用程序然后它将执行某个操作?
答案 0 :(得分:3)
使用描述为here的java.util.prefs.Preferences。我也尝试了谷歌,这是第一个弹出的东西。我们先使用Google。
编辑:
这是一个带注释的文件,用于显示步骤。
定义一个键,每次都可以使用一个String,最好不要用于执行和重构。此密钥稍后将用于访问首选项。
创建Preferences类的实例。
定义一个节点,我喜欢使用类简单名称而不是String。此节点将保存首选项,以便在不同节点中具有相似键的不同首选项时不会发生冲突。
使用get [Type]([KEY],[default_value])访问它并设置[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();
}
}