2

What is the best way to load a property file when path to the property file is not fixed and provided via command line arguments?

I am using the following code to load it but it is giving me null pointer exception when run using command line arguments:

Properties p = new Properties();        
p.load(testClass.class.getResourceAsStream("path to the property file"));
3
  • 2
    Well, I assume that path to the property file is not a valid path. Why would someone provide command line arguments to a path inside your packaged code - that's just weird. Post an MVCE - this is nonsense. Commented Aug 21, 2017 at 7:03
  • Because the same jar will be executed in different environments and hence the path is subject to change. And the path is correctly provided as the same is working fine when run from eclipse by providing the arguments. Commented Aug 21, 2017 at 7:35
  • Sorry; but that's not an MVCE. Commented Aug 21, 2017 at 7:42

1 Answer 1

3

If you get the (full) path via command line, you jsut need to provide a reader or input stream with that path. In the end, your code could look like this:

    public static void main(String[] args) {
            System.out.println("reading property file " + args[0]);

            // create new initial properties
            Properties properties = new Properties();
            // open reader to read the properties file
            try (FileReader in = new FileReader(args[0])){
                // load the properties from that reader
                properties.load(in);
            } catch (IOException e) {
                // handle the exception
                e.printStackTrace();
            }

            // print out what you just read
            Enumeration<?> propertyNames = properties.propertyNames();
            while(propertyNames.hasMoreElements()) {
                String name = propertyNames.nextElement().toString();
                System.out.println(name + ": " + properties.getProperty(name));
            }
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.