简体   繁体   English

是否可以在Java中转换.properties文件,如在C#中的app.config

[英]Is it possible to transform .properties file in java like app.config in C#

I have debug.properties file with debug settings in our project. 我的debug.properties文件在我们的项目中有调试设置。 This file located in repo and each teamate should made changes in this one before debugging. 这个文件位于repo中,每个同伴都应该在调试之前对这个进行更改。

Can I modify this file based on some debug.template.properties file before build like xml transformation in C#? 在构建像C#中的xml转换之前,我可以根据一些debug.template.properties文件修改此文件吗?

You can use cfg4j library and the following code: 您可以使用cfg4j库和以下代码:

private ConfigurationProvider configureProvider() {
    ClassLoader classLoader = getClass().getClassLoader();
    String envPath = classLoader.getResource("properties").getPath();
    Path localPropertiesFilePath = Paths.get(envPath, "local.properties");
    Path basePropertiesFilePath = Paths.get(envPath, "base.properties");

    if (!Files.exists(localPropertiesFilePath)) {
        try {
            Files.createFile(localPropertiesFilePath);
        }
        catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    ConfigFilesProvider localConfigFilesProvider =
            () -> Collections.singletonList(localPropertiesFilePath);
    ConfigFilesProvider baseConfigFilesProvider =
            () -> Collections.singletonList(basePropertiesFilePath);

    ConfigurationSource local = new FilesConfigurationSource(localConfigFilesProvider);
    ConfigurationSource base = new FilesConfigurationSource(baseConfigFilesProvider);
    // If you have 'some' property in base and local files - it takes from local
    ConfigurationSource mergedSource = new MergeConfigurationSource(base, local);

    Environment environment = new ImmutableEnvironment(envPath);

    return new ConfigurationProviderBuilder()
            .withConfigurationSource(mergedSource)
            .withEnvironment(environment)
            .build();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM