user1870400
user1870400

Reputation: 6364

How to load external properties file with Java without rebuilding the Jar?

I use gradle which structures projects in maven style so I have the following

src/main/java/Hello.java and src/main/resources/test.properties

My Hello.java look like this

public class Hello {
    public static void main(String[] args) {
        Properties configProperties = new Properties();
        ClassLoader classLoader =  Hello.class.getClassLoader();
        try {
            configProperties.load(classLoader.getResourceAsStream("test.properties"));
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This works fine. however I want to be able to point to .properties file outside of my project and I want to it to be flexible enough that I can point to any location without rebuilding the jar every time. Is there a way to this without using a File API and passing file path as an argument to the main method?

Upvotes: 1

Views: 1369

Answers (2)

Ashraful Islam
Ashraful Islam

Reputation: 12840

You can try this one, which will first try to load properties file from project home directory so that you don't have to rebuild jar, if not found then will load from classpath

public class Hello {

    public static void main(String[] args) {
        String configPath = "test.properties";

        if (args.length > 0) {
            configPath = args[0];
        } else if (System.getenv("CONFIG_TEST") != null) {
            configPath = System.getenv("CONFIG_TEST");
        }

        File file = new File(configPath);
        try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
            Properties configProperties = new Properties();
            configProperties.load(input);
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

You can send the properties file path as argument or set the path to an environment variable name CONFIG_TEST

Upvotes: 3

Alex Taylor
Alex Taylor

Reputation: 8853

Archaius may be complete overkill for such a simple problem, but it is a great way to manage external properties. It is a library for handling configuration: hierarchies of configuration, configuration from property files, configuration from databases, configuration from user defined sources. It may seem complicated, but you will never have to worry about hand-rolling a half-broken solution to configuration again. The Getting Started page has a section on using a local file as the configuration source.

Upvotes: 1

Related Questions