从Java中的属性文件动态加载

时间:2018-08-24 13:09:14

标签: java apache-commons-config

我有一个config.properties文件,其名称如下:     names = john,jane

然后,我有一个访问该文件并加载名称的类。我还有另一个类,它从某处获取名称,如果该名称在config.properties中,则显示"SUCCESS"。问题是,如果我将名称添加到config.properties,则必须再次运行该程序,它不会动态加载。有什么替代方法?

 public class PropertiesFile {

    private static final char OPENFILES_CONFIG_DELIMITER = ',';
    private static final String OPENFILES_CONFIG = "config.properties";

    private static org.apache.commons.configuration2.Configuration config;

    static {
        try {
            Parameters params = new Parameters();
            FileBasedConfigurationBuilder<FileBasedConfiguration> builder = new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
                .configure(params.properties()
                    .setFileName(OPENFILES_CONFIG)
                    .setListDelimiterHandler(new DefaultListDelimiterHandler(OPENFILES_CONFIG_DELIMITER)));

            config = builder.getConfiguration();    } 
        catch (ConfigurationException cE) {
            //...
        }
    }

    public static Set<String> load() {
        String[] thingsToExecute = config.getStringArray("names");
        return new HashSet<String>(Arrays.asList(thingsToExecute));
    }

}



public class OpenFiles {

    private static Set<String> toExecute;

    public static void main(String[] args) {
        updateToExecute();
        connect();
    }


    private static void connect() {

            //code that obatins JSONObject

            if (obj4.has("name")) {
                String personName = obj4.get("name").toString();
                updateToExecute();
                if (toExecute.contains(personName))   {                                              
                    System.out.println("SUCCESS");
                } else {
                    System.out.println(personName+"is not in the list");
                } 
            }
    }


    private static void updateToExecute() {
        toExecute = PropertiesFile.load();

    }   
}

0 个答案:

没有答案