我想创建一个简单的java程序,在某个地方创建一个文本文件。我想让用户选择该文件夹。但是当我将它包装在jar文件中并发送给其他人时。每次我的朋友运行它,它都会要求提供该文件夹。我想知道如何让jar文件只询问一次并将其设置为final。 在我的.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 :(得分:2)
您需要在某处保存用户配置。有很多方法可以做到这一点,例如你可以使用java.util.prefs包,如Peter Knego在answer to this question中所述:
// 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"
答案 1 :(得分:0)
您可能希望使用属性文件来存储文件夹位置。然后,每次加载jar时都会加载属性