1

i am working on one project and i come to the problem. I need to run .jar over cmnd prompt and i need to put path to .properties file into the argument, for example:

java -jar myproject.jar C:\path\to\config.properties

Now i have a path to file satatic

FileInputStream in = new FileInputStream("config\\crdb.properties");

And i need to somehow put variable instead of static path and change it with argument.

Thank you.

1
  • 2
    that's what args[] in your main function is for Commented Mar 5, 2018 at 9:59

3 Answers 3

1

use -D to put your System variable and use System.getProperty to get it :

  java -Dpath.properties=C:\path\to\config.properties -jar myproject.jar 

String pathProp= System.getProperty("path.properties");
FileInputStream in = new FileInputStream(pathProp);
Sign up to request clarification or add additional context in comments.

Comments

0

Simply use args array:

public static void main(String args[]) {
   try (FileInputStream in = new FileInputStream(args[0])) {
     // do stuff..
   }
}

Comments

0

if you are reading the property file from main method you can simply access command line arguments via args[] array public static void main(String args[]) simple code like below might do

public static void main(String[] args) {
    String splitChar="=";

    try {

        Map<String, String> propertyList = Files.readAllLines(Paths.get(args[0]))
                .stream()
                .map(String.class::cast)
                .collect(Collectors.toMap(line -> line.split(splitChar)[0],
                        line -> line.split(splitChar)[1]));
        System.out.println(propertyList);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

or else you can pass the path as vm option

java -Dfile.path={path to config file} {JavaClassFile to execute}

and you can get the path like below (from any where in your code)

System.getProperty("file.path")

and same as in main method above you can read the property file and put it into a HashMap which I prefer

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.