Reputation: 129
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.
Upvotes: 1
Views: 7429
Reputation: 132
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
Upvotes: 0
Reputation: 2423
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);
Upvotes: 1
Reputation: 34920
Simply use args
array:
public static void main(String args[]) {
try (FileInputStream in = new FileInputStream(args[0])) {
// do stuff..
}
}
Upvotes: 0