2016-02-28 38 views
0

我试图编写一个Java应用程序,但为了使其工作,我需要检查它是否是第一次打开该应用程序与否。有什么办法可以在Mac上做到这一点,如果这是第一次打开应用程序,那么它会执行一定的操作?Java:如何检查一个java应用程序是否已经在mac上运行过

+0

它使用任何数据库或文件吗?可能是我们可以在db或文件中的某些信息中放置某种配置值来存储最后的执行时间。 –

回答

3

使用描述为here的java.util.prefs.Preferences。我也试过谷歌,那是第一个弹出的东西。我们首先使用Google。

编辑:

这里是一个注释文件显示的步骤。

  1. 定义一个键,你可以每次使用一个字符串,最好不要为了执行的目的以及重构。此密钥将用于稍后访问首选项。

  2. 创建Preferences类的实例。

  3. 定义一个节点,我喜欢的一个好选择是使用类简单名称而不是字符串。如果您对不同节点中的相似密钥具有不同的首选项,则此节点将成为保存首选项的位置,以便不会发生冲突。

  4. 使用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(); 

} 
} 
+0

我可以做到这一点。遛狗。一回来就会尽快完成。 – Khanal

+1

完成编辑。感谢指针负责人。 – Khanal

相关问题