2013-04-01 98 views
0

我想製作一個簡單的java程序,在某處創建一個文本文件。我想讓用戶選擇文件夾。但是當我用jar文件包裝併發送給其他人時。每次我的朋友運行它時,它都會要求提供該文件夾。我想知道如何讓jar文件只詢問一次並將其設置爲最終。 在我的java文件,我有一些像用戶偏好

public void setDefaultFolder() { 
    //initially path is empty string 
    if(fc.getPath().equals("")){ 
     String a = JOptionPane.showInputDialog("Please select a default folder." + 
       " Make sure it exists and it's not changeable once set"); 
     if(a != null) { 
     String b = a.replace("\\","\\\\"); 
     // set String path = something users enter 
     // fc is a helper object. I have all the read/write file or other methods 
     // there. I want to let the jar file read the path only for the first time 
     // and set the path final, later on, when it detects path is not empty 
     // string, it stops asking users to type in path. 
     fc.setPath(b); 
     } 
     else { 
      JOptionPane.showMessageDialog(null, "Folder not set"); 
     } 
    } 
} 
+0

將其保存在配置文件中。如果配置文件存在,請閱讀路徑。如果沒有,請詢​​問並保存。 – m0skit0

+0

如何添加一些if語句,如果它是空的,我想讓執行那個JOpitionPane.showInputDialog。如果它不是空的,那麼我不執行輸入對話框。 –

回答

2

你需要在一些地方保存用戶的配置。有很多方法可以做到這一點,例如,你可以使用的java.util.prefs包,在他answer to this question由彼得Knego說:

// Retrieve the user preference node for the package com.mycompany 
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class); 

// Preference key name 
final String PREF_NAME = "name_of_preference"; 

// Set the value of the preference 
String newValue = "a string"; 
prefs.put(PREF_NAME, newValue); 

// Get the value of the preference; 
// default value is returned if the preference does not exist 
String defaultValue = "default string"; 
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string" 
+0

我是否必須創建一個新班級? –

+0

不,檢查了這一點,可能會幫助你: http://alvinalexander.com/blog/post/java/simple-java-preferences-api-example –

+0

如何添加一些if語句,如果它是空的,我想讓執行JOpitionPane.showInputDialog。如果它不是空的,那麼我不執行輸入對話框。 –

0

你可能想使用屬性文件來存儲文件夾位置。您將在每次加載jar時加載屬性

+0

建議你看看...... [道具使用](http://docs.oracle.com/javase/tutorial/essential/environment/properties.html)和[道具示例](http://www.mkyong.com/JAVA/java的屬性文件-實例/) –