firing a command in terminal from java program

2019-08-11 06:19发布

问题:

I need to write a java program which when executed pushes a command into the terminal

I tried using runtime.exec(); but not working fine for me

what i want is "/home/raj/Desktop/java -jar test.jar" to be executed in terminal

Can any one help me to sort it out.

回答1:

If you want to actually start a terminal window (rather than just executing the java process) you will need to launch xterm (or something similar) and tell xterm to run java for example

String command= "/usr/bin/xterm -e /home/raj/Desktop/java -jar test.jar"; 
Runtime rt = Runtime.getRuntime();      
Process pr = rt.exec(command);


回答2:

Please refer following example .with list of arguments to java program.

Process proc = null;
try {
    String cmd[] = {"gnome-terminal", "-x", "bash", "-c", "ls; echo '<enter>'; read" };


    proc = Runtime.getRuntime().exec(cmd, null, wd);
} catch (IOException e) {
    e.printStackTrace();
}


回答3:

You can use full path of the jar file as an argument to "java"

String command= "java -jar /home/raj/Desktop/test.jar"; 
Runtime rt = Runtime.getRuntime();      
Process pr = rt.exec(command);


标签: java linux shell