You can use Runtime#exec for that.
The following snippet shows how you can read the output of a certain command executed in cmd.exe.
public static String executeCommand(String command) throws IOException
{
StringBuilder outputBuilder = new StringBuilder();
Process process = Runtime.getRuntime().exec(new String[] {"cmd", "/c", command});
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String read = null;
while((read = outputReader.readLine()) != null)
{
outputBuilder.append(read).append("\n");
}
outputReader.close();
process.destroy();
return outputBuilder.toString();
}
The following example shows how to communicate with a process interactively.
public static void main(String[] args) throws Exception {
Process process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", "cmd" /* Replace with the name of the executable */});
Scanner scanner = new Scanner(System.in);
PrintWriter printWriter = new PrintWriter(process.getOutputStream());
BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
new Thread(() -> {
try {
String read = null;
while ((read = outputReader.readLine()) != null) {
System.out.println("Process -> " + read);
}
System.out.println("Finished executing.");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
while (scanner.hasNext()) {
String cmd = scanner.nextLine();
System.out.println(cmd + " -> Process");
printWriter.write(cmd + "\n");
printWriter.flush();
}
scanner.close();
printWriter.close();
outputReader.close();
process.destroy();
}