I would like to know, is there a way to let a java application open command prompt (cmd.exe) and type/execute commands, preferably without the user seeing the command prompt window.
If anyone knows a sample application or a piece of code that can do this, your answer will be appreciated!
The java.lang.ProcessBuilder and java.lang.Process classes are available for executing and communicating with external programs. With an instance of the java.lang.ProcessBuilder class, it can execute an external program and return an instance of a subclass of java.lang.Process. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.
public class ProcessBuildDemo {
public static void main(String [] args) throws IOException {
String[] command = {"CMD", "/C", "dir"};
ProcessBuilder probuilder = new ProcessBuilder( command );
//You can set up your work directory
probuilder.directory(new File("c:\\xyzwsdemo"));
Process process = probuilder.start();
//Read out dir output
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:\n",
Arrays.toString(command));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Wait to get exit value
try {
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
use below code to execute process using java.
final List<String> commands = new ArrayList<String>();
commands.add("cmd");
commands.add(input2); // second commandline argument
commands.add(input3);// third commandline agrument
ProcessBuilder pb = new ProcessBuilder(commands);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With