0

I have to write a program that reads(eg .csv), filters/sorts and writes(eg .html) a given file by the user.

It should look like that when the user is starting the program in the terminal:

java -jar MyProgram.jar --input=C:\Path\to\InputFile.csv --output=C:\Path\to\OutputFile.html

but it should also take args for filtering and/or sorting, without any order:

java -jar MyProgram.jar --Genre=Rock --input=C:\Path\to\InputFile.csv --DateFrom:1980 --output=C:\Path\to\OutputFile.html --DateTo=2000

Also if the user enters the wrong args (eg Gnre= instead of Genre=), the program should not end and instead ask the user to correct the input.

I have already tried to code something for the in and output but I am sure that there are better ways to do so, my example isn't good practice.

public static void main(String[] args) {

    final String inputFlag ="--input";
    final String outputFlag ="--output";

    String inputFileLocation = null;
    String outputFileLocation = null;

    if (args.length >= 1) {
        for (String arg : args) {
            String[] userArgs = arg.split("=");

            if (userArgs[0].equals(inputFlag)) {
                inputFileLocation = userArgs[1];
                System.out.println("Input: " + userArgs[1]);
            }
            if (userArgs[0].equals(outputFlag)) {
                outputFileLocation = userArgs[1];
                System.out.println("Output: " + userArgs[1]);
            }
        }
    } else {
        System.out.println("You need to enter at least 2 args: [--input=, --output=]");
    }

Is there a common way of handling args? If I have, let's say 30 elements in my CSV, I would have 30 ifs.

I would be happy if you could help me by giving me some input on how to solve that program in a "good practice"-way.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
codepanda
  • 9
  • 2
  • 1
    Generally, when writing a console program that is controlled through command line parameters and usually runs without further user input, it is considered best practice to *not* suddenly block and wait for user input on an error. That makes it harder to use your program in any sort of script. –  Aug 25 '20 at 09:41
  • 3
    "*Is there a common way of handling args?*" - https://commons.apache.org/proper/commons-cli/ –  Aug 25 '20 at 09:41
  • I found this stackoverflow question which you might find interesting : https://stackoverflow.com/questions/20571432/code-structure-for-parsing-command-line-arguments-in-java Its approved answer is using jcommander : http://jcommander.org/ – planben Aug 25 '20 at 10:02

0 Answers0