2013-04-01 100 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的属性文件-实例/) –