JavaFX 项目的配置文件

Config-file for JavaFX-Project

我想添加一个文件或 class 到我的 JavaFX 项目,它只包含项目的配置数据,例如数据库的访问数据、系统路径等。你会怎么做? 把所有东西都写成正常的class?肯定有更好的方法吧?

你说得对,我当然很乐意这样做。 首先我在项目文件夹中创建了一个 属性 文件并将其命名为 app.properties:

db_url=jdbc:mysql://localhost:3306/db name
db_user=user name
db_pwd=secret password
instructions_folder=/home/username/documents/

然后我创建了一个 class 来加载属性并使它们在整个项目中可用。

public class AppProperties {

    // FILENAME = Path to properties-file
    // Store and protect it where ever you want
    private final String FILENAME = "app.properties";
    
    private static final AppProperties config_file = new AppProperties();
    private Properties prop = new Properties();
    private String msg = "";

    private AppProperties(){
        InputStream input = null;

        try{
            input = new FileInputStream(FILENAME);

            // Load a properties
            prop.load(input);
        }catch(IOException ex){
            msg = "Can't find/open property file";
            ex.printStackTrace();
        }finally{
            if (input != null){
                try{
                    input.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
            }

        }
    }

    public String getProperty (String key){
        return prop.getProperty(key);
    }

    public String getMsg () {
        return msg;
    }

    // == Singleton design pattern == //
    // Where ever you call this methode in application
    // you always get the same and only instance (config_file)
    public static AppProperties getInstance(){
        return config_file;
    }
}

在我进行数据库查询的 DBUtilitis class 中,我现在将属性加载到最终变量中并在查询方法中使用它们。

private static final String db_url = AppProperties.getInstance().getProperty("db_url");
    private static final String db_user = AppProperties.getInstance().getProperty("db_user");
    private static final String db_pwd = AppProperties.getInstance().getProperty("db_pwd");

如果我没有完全误解这一点,属性 文件的优点是它们可以存储在服务器上的某个位置并受到保护。我希望解决方案不是完全错误的 - 无论如何它都能正常工作。我总是很高兴收到建议和/或改进。