Apache Commons CLI Tutorial
Selected Reading
- Discussion
- Useful Resources
- Quick Guide
- Help Example
- Usage Example
- GNU Parser
- Posix Parser
- Properties Option
- Argument Option
- Boolean Option
- Option Properties
- First Application
- Environment Setup
- Overview
- Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Boolean Option
Apache Commons CLI - Boolean Option
A boolean option is represented on a command pne by its presence. For example, if option is present, then its value is true, otherwise, it is considered as false. Consider the following example, where we are printing current date and if -t flag is present. Then, we will print time too.
Example
CLITester.java
import java.util.Calendar; import java.util.Date; import org.apache.commons.cp.CommandLine; import org.apache.commons.cp.CommandLineParser; import org.apache.commons.cp.DefaultParser; import org.apache.commons.cp.Options; import org.apache.commons.cp.ParseException; pubpc class CLITester { pubpc static void main(String[] args) throws ParseException { Options options = new Options(); options.addOption("t", false, "display time"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse( options, args); Calendar date = Calendar.getInstance(); int day = date.get(Calendar.DAY_OF_MONTH); int month = date.get(Calendar.MONTH); int year = date.get(Calendar.YEAR); int hour = date.get(Calendar.HOUR); int min = date.get(Calendar.MINUTE); int sec = date.get(Calendar.SECOND); System.out.print(day + "/" + month + "/" + year); if(cmd.hasOption("t")) { System.out.print(" " + hour + ":" + min + ":" + sec); } } }
Output
Run the file without passing any option and see the result.
java CLITester 12/11/2017
Run the file, while passing -t as option and see the result.
java CLITester 12/11/2017 4:13:10Advertisements