Search code examples
javacommand-line-argumentsargs

Parsing command line args[], with flags and without using a third party lib


I have a requirement to parse some command line arguments in a Java application without using any third party libraries (like Apache CLI or JCommander). I can only use the standard Java 11 API.

They will be passed into my application on start up and with flags; e.g: java myClass -port 14008 -ip 140.086.12.12 which can be in any order.

I'm pretty new to Java, but how would I go about doing this. Can any standard API functions help with this? Or should I check them manually e.g: if arg[0] = "-port" then arg[0]+1 = port number.


Solution

  • This is how I solved the problem. It assumes there are class member variables set with default values to overide.

    private String ipAddress = "localhost";

    private Integer port = 14001;

         /**
         * Method to get the ip and port number from the command line args.
         * It caters for any order of flag entry.It tries to override the
         * defaults set as a class variables, so if it can't, it uses those.
         *
         * @param args The args passed in by the user.
         */
        private void getPortAndIp(String[] args) {
            System.out.println("Getting inputs ");
            if ((args[0].equals("-ccp")) && (args.length == 2)) {
                this.port = Integer.parseInt(args[1]);
            } else if ((args[0].equals("-cca")) && (args.length == 2)) {
                this.ipAddress = args[1];
            } else if ((args[0].equals("-ccp")) && (args[2].equals("-cca"))
                    && (args.length == 4)) {
                this.port = Integer.parseInt(args[1]);
                this.ipAddress = args[3];
            } else if ((args[0].equals("-cca")) && (args[2].equals("-ccp"))
                    && (args.length == 4)) {
                this.port = Integer.parseInt(args[3]);
                this.ipAddress = args[1];
            } else {
                System.out.println("Options:");
                System.out.println("-ccp [port number]");
                System.out.println("-cca [ip address]");
                System.out.println("Could not determine port from command line " +
                        "arguments, using defaults: ");
            }
            System.out.println("on " + this.ipAddress + ":" + this.port);
        }