猿问

在java中使用.properties文件中的引用合并字符串

我的代码:


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");

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


四季花海
浏览 276回答 2
2回答

德玛西亚99

您是否考虑过使用 Apache 的commons-configuration?要添加的依赖项pom.xml<dependency>&nbsp; &nbsp; <groupId>commons-configuration</groupId>&nbsp; &nbsp; <artifactId>commons-configuration</artifactId>&nbsp; &nbsp; <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 {&nbsp; &nbsp; private CompositeConfiguration config;&nbsp; &nbsp; public void getConstants() throws ConfigurationException {&nbsp; &nbsp; &nbsp; &nbsp; config = new CompositeConfiguration();&nbsp; &nbsp; &nbsp; &nbsp; config.addConfiguration(new PropertiesConfiguration("test.properties"));&nbsp; &nbsp; }&nbsp; &nbsp; public CompositeConfiguration getConfig() {&nbsp; &nbsp; &nbsp; &nbsp; return config;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String... args) throws ConfigurationException {&nbsp; &nbsp; &nbsp; &nbsp; Configurations config = new Configurations();&nbsp; &nbsp; &nbsp; &nbsp; config.getConstants();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(config.getConfig().getString("SOURCE"));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(config.getConfig().getString("SOURCES"));&nbsp; &nbsp; }}测试属性SOURCE=SourceSOURCES=${SOURCE}sDESTINATION=DestinationDESTINATIONS=${DESTINATION}s

人到中年有点甜

您可以在属性文件中使用“%s”进行字符串组合:SOURCE=Source SOURCES=%ss然后,您必须格式化字符串:public&nbsp;static&nbsp;String&nbsp;SOURCES&nbsp;=&nbsp;String.format(prop.getProperty("SOURCES"),&nbsp;prop.getProperty("SOURCE"));
随时随地看视频慕课网APP

相关分类

Java
我要回答