[英]How to run Java method with arguments from command line?
I am trying to run the following method in Loader.java
from the command line:我正在尝试从命令行在Loader.java
中运行以下方法:
public static void method(String path, String word)
As seen above, I must pass in the variables path
and word
, and I want the command line to display the System.out.println()
's in the method.如上所示,我必须传入变量path
和word
,并且我希望命令行在方法中显示System.out.println()
。
What command can I run to do this?我可以运行什么命令来做到这一点?
Note: when I run the following commands,注意:当我运行以下命令时,
javac *.java
jar -cvf Loader.jar Loader.class
java -cp ./Loader.jar Loader
I get the following error:我收到以下错误:
Caused by: java.lang.NoClassDefFoundError: path/to/Loader (wrong name: Loader)
What must I do to successfully run method
from the command line?我必须怎么做才能从命令行成功运行method
?
Here is minimum reproducible version of Loader.java
:这是Loader.java
的最低可重现版本:
public class Loader {
public static void main(String[] args) {
method("my/path", "my_word");
}
public static void method(String path, String word) {
System.out.println("Output after doing something");
}
}
Just do the following:只需执行以下操作:
javac Loader.java
java Loader
In fact, if you are you Java-11 or above, you don't even need to use the first command ie you can directly use the following command:事实上,如果你是Java-11或以上,你甚至不需要使用第一个命令,你可以直接使用以下命令:
java Loader.java
However, if you want to create a jar file and execute the class from it, execute the steps given below:但是,如果要创建 jar 文件并从中执行 class,请执行以下步骤:
mkdir demo
cd demo
Now create/place Loader.java
in this folder.现在在此文件夹中创建/放置Loader.java
。 Then,然后,
javac *.java
jar -cvf loader.jar .
java -cp loader.jar Loader
Note that I've used a new directory, demo
to make it clear but it is not necessary.请注意,我使用了一个新目录demo
来说明清楚,但这不是必需的。 Another thing you should notice is the .
您应该注意的另一件事是.
at the end of jar
command which specifies the current directory.在jar
命令的末尾指定当前目录。
String[] args
parameter in main
stores all the parameters from the command-line eg if you run the following program as java Loader my/path my_word
from the command-line, main
中的String[] args
参数存储命令行中的所有参数,例如,如果您将以下程序作为java Loader my/path my_word
从命令行运行,
public class Loader {
public static void main(String[] args) {
if (args.length >= 2) {
method(args[0], args[1]);
} else {
System.out.println("Command line parameters are missing");
}
}
public static void method(String path, String word) {
System.out.println("Path: " + path);
System.out.println("Word: " + word);
}
}
the output will be output 将是
Path: my/path
Word: my_word
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.