A couple of things that are going wrong here:
- We need to pass our command as string tokens to the exec () command
- We need to wait for the process to complete using process.waitFor () instead of the sleeping one, this will block the current thread, so if you do not want you to need to execute this on another thread or use the ExecutorService.
- It is recommended to check the output value of waitFor () to see if our command was executed correctly (value 0) or not (any other value, usually positive 1 in case of unsuccessful execution)
- Optionally (to see the result) we need to redirect the standard OUT and ERR somewhere, say, print it to console (), although you can put it in a file with some GUI, etc.
So, at a minimum, the following code should work:
Process process = Runtime.getRuntime().exec(new String[] {"cmd", "/c", "cd", "C:\\dev", "&&", "dir"}); int outputVal = process.waitFor(); boolean alive = process.isAlive(); System.out.format("alive %s, outputVal: %d\n",alive, outputVal);
Further suggestions:
- use ProcessBuilder instead of runTime.exec (), it allows more control and this is recommended since JDK 1.5
- read inputStream command
So, the code will look something like this:
List<String> cmdList = Arrays.asList("cmd", "/c", "cd", "C:\\dev", "&&", "dir"); ProcessBuilder pb = new ProcessBuilder(cmdList); pb.redirectErrorStream(true); //redirect STD ERR to STD OUT Process process = pb.start(); try (final BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line = null; while ((line = br.readLine()) != null) { System.out.println("std-out-line: " + line); } } int outputVal = process.waitFor(); System.out.format("outputVal: %d\n", outputVal);
Since waitFor () is a blocking call, you can execute it in a separate thread or using the executing service. Sample code here:
final StringBuffer outputSb = new StringBuffer(); ExecutorService executorService = null; try { executorService = Executors.newSingleThreadExecutor(); final Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { try (final BufferedReader br = new BufferedReader( new InputStreamReader(process.getInputStream()))) { String line = null; while ((line = br.readLine()) != null) { outputSb.append("std-out-line: "); outputSb.append(line); outputSb.append('\n'); } } int exitValue = process.waitFor(); System.out.format("exitValue: %d\n", exitValue); return exitValue; } }); while (!future.isDone()) { System.out.println("Waiting for command to finish doing something else.."); Thread.sleep(1 * 1000); } int exitValue = future.get(); System.out.println("Output: " + outputSb); } finally { executorService.shutdown(); }
source share