Java 中如何处理 main() 参数的一些信息

Some informations of how handle the main() args in Java

我必须开发一个命令行 Java 应用程序,其中 main() 方法接受 2 个分别命名为 partitaIVAnomePDF[ 的字符串参数=32=].

因此,作为起点,我创建了这个简单的 Main class:

public class Main {

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

我认为我可以从 Windows 控制台执行这个简约的应用程序,并且我可以在 Windows 控制台(或在Linux shell):

java Main 123456789 myDocument.pdf

而且我认为我可以在我的应用程序中以这种方式修改原始代码来检索它:

public class Main {

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

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

所以现在我对这个话题有两个疑问:

1) 我知道我可以使用 Windows 命令行或 Linux shell 指定我的 2 个参数来执行此应用程序,但是我可以对我的 IDE控制台?具体在IntelliJ的运行标签中?

2)我可以通过某种方式指定用户可以指定的参数只有2个吗?

1)有个东西叫run/debug配置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)不行,只能打印错误引导用户

在 Intellij (Linux) 中,您可以:

Press Alt + Shift + F10 (the run shortcut)

Press right key

Go down to Edit

Then press Tab to go to "Program arguments".

这是您在 IntelliJ 中传递参数的地方。之后只需点击 运行。

您应该花时间学习现代 CLI 参数解析器:

我更喜欢JewelCli

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

这里有一个例子可以作为基础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();
}

}