【问题标题】:Merge string using references in .properties file in java在java中使用.properties文件中的引用合并字符串
【发布时间】:2019-02-05 10:10:37
【问题描述】:

我的代码:

public static InputStream input = null;
public static Properties prop = new Properties();

static public void getConstants(){ 
    Constants constants = new ConstantsEng();
    try {

        input = CLASS_NAME.class.getClassLoader().getResourceAsStream("FILE_NAME.properties");

        prop.load(input);
    } catch (IOException e) {
        e.printStackTrace();
    }

public static String SOURCE = prop.getProperty("SOURCE");
public static String SOURCES = prop.getProperty("SOURCES");
public static String DESTINATION = prop.getProperty("DESTINATION");
public static String DESTINATIONS = prop.getProperty("DESTINATIONS");

FILE_NAME.properties

SOURCE=Source
SOURCES=${SOURCE}s
DESTINATION=Destination
DESTINATIONS=${DESTINATION}s

字符串在渲染时会显示占位符:

我想在我的 .properties 文件中重用字符串,但此代码不起作用。有没有办法解决它,还是我犯了一个错误?

当我获取时:

public static String SOURCES = prop.getProperty("SOURCES");

我期待“来源”作为输出。

【问题讨论】:

  • 你能发布预期的输出而不是发布图片吗?
  • 当我获取 public static String SOURCES = prop.getProperty("SOURCES");我期待“来源”作为输出。

标签: java properties-file application.properties


【解决方案1】:

您是否考虑过使用 Apache 的 commons-configuration

pom.xml中添加依赖

<dependency>
    <groupId>commons-configuration</groupId>
    <artifactId>commons-configuration</artifactId>
    <version>1.6</version>
</dependency>

你的班级会是这样的

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class Configurations {
    private CompositeConfiguration config;

    public void getConstants() throws ConfigurationException {
        config = new CompositeConfiguration();
        config.addConfiguration(new PropertiesConfiguration("test.properties"));
    }

    public CompositeConfiguration getConfig() {
        return config;
    }

    public static void main(String... args) throws ConfigurationException {
        Configurations config = new Configurations();
        config.getConstants();

        System.out.println(config.getConfig().getString("SOURCE"));
        System.out.println(config.getConfig().getString("SOURCES"));
    }
}

test.properties

SOURCE=Source
SOURCES=${SOURCE}s
DESTINATION=Destination
DESTINATIONS=${DESTINATION}s

【讨论】:

    【解决方案2】:

    您可以在属性文件中使用“%s”进行字符串组合:

    SOURCE=Source
    SOURCES=%ss
    

    然后,您必须格式化字符串:

    public static String SOURCES = String.format(prop.getProperty("SOURCES"), prop.getProperty("SOURCE"));
    

    【讨论】:

      猜你喜欢
      • 2015-09-19
      • 1970-01-01
      • 2015-07-21
      • 2019-08-17
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      相关资源
      最近更新 更多