How to Invoke JAR Methods on Linux
There are two ways to invoke a method in a jar file in a Linux system: using the Java command line tool or invoking through Java code.
- Call the methods within a jar file using Java command line tools.
java -cp path/to/your.jar com.yourpackage.YourClass
The -cp parameter is used to specify the path of the jar file, with com.yourpackage.YourClass being the name of the class to be called.
- Invoke methods in a jar file using Java code.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
try {
Process proc = Runtime.getRuntime().exec("java -jar path/to/your.jar");
InputStream in = proc.getInputStream();
// 读取jar包里的输出
int c;
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
in.close();
// 获取调用jar包的返回值
int exitVal = proc.waitFor();
System.out.println("\nExited with error code " + exitVal);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
This code snippet will start a new process to run the jar file and read its output. You can modify the code as needed to meet your requirements.