Java 中的命令行参数是什么?
如何访问java命令行参数?
在 java 中访问命令行参数的方法非常简单。在我们的 java 代码中使用这些参数很简单。它们存储为传递给main()的字符串数组。它主要被命名为args。看看下面代码片段中的公共标头。
public static void main(String[] args){…}
例子
让我们看一个下面详细解释的例子。
// Program to check for command line arguments
public class Example {
public static void main(String[] args) {
// check if the length of args array is < 0
if (args.length <= 0) {
System.out.println("No command line arguments found.");
} else {
System.out.println("The first command line argument is: " + args[0]);
System.out.println("All of the command line arguments are: ");
// iterating the args array and printing all of the command line arguments
for (String index : args)
System.out.println(index);
}
}
}
执行
要执行该程序,请按以下方式在命令行上传递参数。我们在这里使用 IntelliJ IDE,您可以使用任何您的选择。对于 IntelliJ,选择选项“运行”→“编辑配置”。 接下来,转到可用选项卡上第二个的“程序参数”选项卡。您可以在可用的块中输入参数,单击“确定”,然后单击“运行”。 对于与此程序相同的输出,请使用下面的文本。
我的名字是安德鲁。
输出
第一个命令行参数是:My 所有命令行参数是:My name is Andrew。
GO TO FULL VERSION