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

有关如何在Java中处理main()参数的一些信息,java,intellij-idea,main,args,Java,Intellij Idea,Main,Args,我必须开发一个命令行Java应用程序,其中main()方法接受两个字符串参数,分别命名为partitaIVA和nomePDF 因此,作为起点,我创建了这个简单的Main类: public class Main { public static void main(String[] args) { System.out.println("Hello World !!!"); } } 我认为我可以从Windows控制台执行这个简约的应用程序,我可以在Windows控

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

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

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World !!!");
    }
}
我认为我可以从Windows控制台执行这个简约的应用程序,我可以在Windows控制台(或Linux shell)中执行这些参数的应用程序:

我认为我可以在我的应用程序中检索它,并通过以下方式修改原始代码:

public class Main {

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

        String partitaIVA = args[0];
        String nomePDF = args[1];
    }
}
所以现在我对这个话题有两个疑问:

1) 我知道我可以使用Windows命令行或Linuxshell来指定我的2个参数来执行这个应用程序,但是我可以在IDE控制台中执行同样的操作吗?特别是在IntelliJ的运行选项卡中

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

1)有一种称为运行/调试配置(这里还有一些关于特定选项的详细信息:)

2) 否,您只能在Intellij(Linux)中打印错误并引导用户执行以下操作:

按Alt+Shift+F10(跑步快捷方式)

按右键

下楼编辑

然后按Tab键转到“程序参数”

这是在IntelliJ中传递Arumgins的地方。在那之后,我就开始跑步了

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


com.lexicalscope.jewelcli
朱厄克利
0.8.9
下面是一个可以用作基类的示例:
公共类主
{
私有静态最终记录器日志;
静止的
{
LOG=LoggerFactory.getLogger(Main.class);
}
私有静态Args init(@Nonnull final String[]Args)
{
final Cli=CliFactory.createCli(Args.class);
尝试
{
返回cli.parseArguments(args);
}
捕获(最终参数ValidationException e)
{
对于(最终验证失败vf:e.getValidationFailures())
{
LOG.error(vf.getMessage());
}
LOG.info(cli.getHelpMessage());
System.exit(2);//参数解析错误的Bash标准
return null;//这是为了让编译器满意!
}
}
私有静态列表parseKey(@Nonnull final String key)
{
返回新的ArrayList(Arrays.asList(key.toLowerCase().split(“\\”));
}
@抑制警告(“未选中”)
私有静态映射addNode(@Nonnull映射节点,@Nonnull最终列表键,@Nonnull最终字符串值)
{
if(key.isEmpty())
{
返回节点;
}
else if(keys.size()==1)
{
node.put(key.remove(0),value.trim());
返回节点;
}
else if(node.containsKey(key.get(0)))
{
返回addNode((Map)node.get(key.remove(0)),key,value);
}
其他的
{
final Map=new HashMap();
node.put(key.remove(0),map);
返回addNode(映射、键、值);
}
}
公共静态void main(最终字符串[]args)
{
尝试
{
最终参数a=init(参数);
最终属性p=新属性();
p、 加载(新文件输入流(a.getInputFile());
最终HashMap根=新HashMap();
for(最终字符串键:p.stringPropertyNames())
{
addNode(root,parseKey(key),p.getProperty(key));
}
开关(a.getFormat().toLowerCase().charAt(0))
{
案例“j”:LOG.info(mapToJson(根));break;
案例“b”:LOG.info(Strings.bytesToHex(mapToCbor(root));break;
案例“x”:LOG.error(“此时未实现XML!”);break;
默认值:LOG.error(“无效格式{}”,a.getFormat());
}
}
捕获(IOE异常)
{
抛出新的运行时异常(e);
}
}
接口参数
{
@选项(shortName=“i”,longName=“input”,description=“要读取的属性文件”)
文件getInputFile();
@选项(shortName=“o”,longName=“output”,description=“要输出到的JSON文件。”)
文件getOutputFile();
@选项(shortName=“f”,longName=“format”,description=“输出Json的格式|二进制| Xml”)
字符串getFormat();
@选项(helpRequest=true,description=“Display Help”,shortName=“h”)
布尔getHelp();
}

}

应该有一个类似于
运行配置的设置(在Eclipse中就是这么叫的),您可以在其中传递命令行参数。寻找可能的
运行…
。不,没有办法限制用户传入两个参数,但是您可以安全地忽略其余的参数,或者抛出错误,或者根据需要进行处理。
public class Main {

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

        String partitaIVA = args[0];
        String nomePDF = args[1];
    }
}
<dependency>
    <groupId>com.lexicalscope.jewelcli</groupId>
    <artifactId>jewelcli</artifactId>
    <version>0.8.9</version>
</dependency>
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();
}