I have a properties file that looks like this:
hostName=machineA.domain.host.com emailFrom=tester@host.com emailTo=world@host.com emailCc=hello@host.com
And now I read the above properties file from my Java program as
public class FileReaderTask { private static String hostName; private static String emailFrom; private static String emailTo; private static String emailCc; private static final String configFileName = "config.properties"; private static final Properties prop = new Properties(); public static void main(String[] args) { readConfig(arguments); } private static void readConfig(String[] args) throws FileNotFoundException, IOException { if (!TestUtils.isEmpty(args) && args.length != 0) { prop.load(new FileInputStream(args[0])); } else { prop.load(FileReaderTask.class.getClassLoader().getResourceAsStream(configFileName)); } hostName = prop.getProperty("hostName").trim(); emailFrom = prop.getProperty("emailFrom").trim(); emailTo = prop.getProperty("emailTo").trim(); emailCc = prop.getProperty("emailCc").trim(); } }
In most cases, I will run my above program through the command line as an executable jar like this -
java -jar abc.jar config.properties
My questions -
- Is there any way to override the above attributes in the properties file via the command line without touching the file, if necessary? Since I do not want to change the config.properties file whenever I need to change the value of attributes? Can this be done?
Something like this should override the hostName value in the file?
java -jar abc.jar config.properties hostName=machineB.domain.host.com
- And is there also a way to add
--help while abc.jar , which can tell us more about how to run the jar file and what each property means and how to use them? I saw --help while running most of the C ++ or Unix executable, so not sure how we can do the same in Java?
Do I need to use CommandLine parser for this in Java to achieve both things?
source share