-5

I have to develop a command line Java application in which the main() method accept 2 String parameters named respetivelly partitaIVA and nomePDF.

So, as starting point, I created this simple Main class:

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World !!!");
    }
}

I think that I can perform this minimalistic application from the Windows console and that I can perform my application passion these parameters to it doing something like this in the Windows console (or in the Linux shell):

java Main 123456789 myDocument.pdf

and I think that I can retrieve it inside my application modifying the original code in this way:

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World !!!");

        String partitaIVA = args[0];
        String nomePDF = args[1];
    }
}

So now I have 2 doubts about this topic:

1) I know that I can perform this application specifying my 2 parameters using the Windows command line or the Linux shell but can I do the same thing into my IDE console? Specifically in the Run tab of IntelliJ?

2) Can I specify in some way that the parameters that the user can specify are only 2?

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 2
    There should be a setting like `Run Configurations` (that's what it's called in Eclipse) where you can pass in command line arguments. Look for maybe `Run...`. No, there is no way to limit the user passing in two, but you can safely ignore the remaining arguments, or throw an error, or handle it however you want. – Kon Feb 10 '15 at 16:44

3 Answers3

1

1) There is something called run/debug configuration https://www.jetbrains.com/idea/help/creating-and-editing-run-debug-configurations.html (here are also sone details about the specific options you have: https://www.jetbrains.com/idea/help/creating-and-editing-run-debug-configurations.html#d1628194e152)

2) No, you can only print an error and guide the user

Leander
  • 1,322
  • 4
  • 16
  • 31
1

You should invest the time in learning a modern CLI argument parser:

I prefer JewelCli

<dependency>
    <groupId>com.lexicalscope.jewelcli</groupId>
    <artifactId>jewelcli</artifactId>
    <version>0.8.9</version>
</dependency>

Here is an example that can be used as a base class:

public class Main
{
private static final Logger LOG;

static
{
    LOG = LoggerFactory.getLogger(Main.class);
}

private static Args init(@Nonnull final String[] args)
{
    final Cli<Args> cli = CliFactory.createCli(Args.class);
    try
    {
        return cli.parseArguments(args);
    }
    catch (final ArgumentValidationException e)
    {
        for (final ValidationFailure vf : e.getValidationFailures())
        {
            LOG.error(vf.getMessage());
        }
        LOG.info(cli.getHelpMessage());
        System.exit(2); // Bash standard for arg parsing errors
        return null; // This is to make the compiler happy!
    }
}

private static List<String> parseKey(@Nonnull final String key)
{
    return new ArrayList<String>(Arrays.asList(key.toLowerCase().split("\\.")));
}

@SuppressWarnings("unchecked")
private static Map<String, Object> addNode(@Nonnull Map<String, Object> node, @Nonnull final List<String> keys, @Nonnull final String value)
{
    if (keys.isEmpty())
    {
        return node;
    }
    else if (keys.size() == 1)
    {
        node.put(keys.remove(0), value.trim());
        return node;
    }
    else if (node.containsKey(keys.get(0)))
    {
        return addNode((Map<String, Object>) node.get(keys.remove(0)), keys, value);
    }
    else
    {
        final Map<String, Object> map = new HashMap<String, Object>();
        node.put(keys.remove(0), map);
        return addNode(map, keys, value);
    }
}

public static void main(final String[] args)
{
    try
    {
        final Args a = init(args);
        final Properties p = new Properties();
        p.load(new FileInputStream(a.getInputFile()));
        final HashMap<String, Object> root = new HashMap<String, Object>();
        for (final String key : p.stringPropertyNames())
        {
            addNode(root, parseKey(key), p.getProperty(key));
        }
        switch (a.getFormat().toLowerCase().charAt(0))
        {
            case 'j': LOG.info(mapToJson(root)); break;
            case 'b' : LOG.info(Strings.bytesToHex(mapToCbor(root))); break;
            case 'x' : LOG.error("XML not implemented at this time!"); break;
            default : LOG.error("Invalid format {}", a.getFormat());
        }
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
}

interface Args
{
    @Option(shortName = "i", longName = "input", description = "Properties file to read from.")
    File getInputFile();

    @Option(shortName = "o", longName = "output", description = "JSON file to output to.")
    File getOutputFile();

    @Option(shortName = "f", longName = "format", description = "Format of output Json|Binary|Xml")
    String getFormat();

    @Option(helpRequest = true, description = "Display Help", shortName = "h")
    boolean getHelp();
}

}

0

In Intellij (Linux) you do:

Press Alt + Shift + F10 (the run shortcut)

Press right key

Go down to Edit

Then press Tab to go to "Program arguments".

This is where you pass the arugments in IntelliJ. After that just hit run.

Brunaldo
  • 66
  • 6