What do we want to do when our jar package executes the program through the main method? Here is an example:
import java.io.IOException;
import java.util.Scanner;
/**
* @author dongzy
* @date 2017/12/25.
*/
public class TestMainClass {
public static void main(String[]args){
for (int i = 0; i <args.length; i++) {
System.out.println("The first"+i+"Parameters are:"+args[i]);
}
if(args.length <= 0 ){
scannerInput();
}else {
inputByArgs(args);
}
killProcess();
}
private static void killProcess() {
Runtime rt = Runtime.getRuntime();
Process p = null;
try {
rt.exec("cmd.exe /C start wmic process where name='cmd.exe' call terminate");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void inputByArgs(String[] args) {
for (int i = 0; i < args.length; i++) {
doSomething(args[i]);
}
}
private static void scannerInput() {
Scanner scanner = new Scanner(System.in);
while (true){
System.out.print("Please enter a number:");
String a = scanner.nextLine();
if(a.equals("exit")){
killProcess();
}else {
doSomething(a);
}
}
}
private static void doSomething(String a) {
switch (a){
case "0":
System.out.println("You entered 0");
break;
case "1":
System.out.println("You entered 1");
break;
default:
System.out.println("Please re-enter:");
break;
}
}
}
When you enter Java - CP test.jar testmainclass in the cmd window, you will be prompted as follows:
What if you want to directly transfer the data as parameters, then judge the data in args, and perform the corresponding operations? The above code has pasted the method, which can be pasted and run. How to write the bat configuration file
When you enter Java - CP test.jar testmainclass 0 1 in the cmd window, the data in args is an array of 0 and 1, which is so simple.