简体   繁体   中英

Java: Load multiple properties files as one

Sorry if the title is unclear.

What I'm trying to do is load configuration files "on top of each other".

Say I have Config #1:

config.property=Something Here

And Config #2:

config.otherproperty=Other Thingy Here

And the java app loads it as this:

config.property=Something Here

config.otherproperty=Other Thingy Here

As though it was all one file.

How would I do this?

Use java.util.Properties with the defaults constructor parameter. Whichever one should over-ride the other in the event of any conflicts should be constructed last, with the other as the defaults.

I am unclear as to what you really need. If I understood you correctly, you want to load two properties file into a single Properties object. If this is the case, the all you have to do is something like this:

PropsDemo demo = new PropsDemo();
String prop1 = "config1.properties";
String prop2 = "config2.properties";

Properties props = new Properties();
InputStream input1 = demo.getClass().getClassLoader().getResourceAsStream(prop1);
InputStream input2 = demo.getClass().getClassLoader().getResourceAsStream(prop2);
try
{
    props.load(input1);
    props.load(input2);
    System.out.println(props.toString());
}
catch (IOException e)
{
    System.out.println("Something went wrong!");
}

The file config1.properties contains:

color=blue

And the file config2.properties contains:

shape=circle

The snippet above outputs:

{shape=circle, color=blue}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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