This example demonstrate how to run system commnad ("dir" in Windows) from Java code, and read the output of the command, using
Runtime.getRuntime().exec().
package java_process;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @web java-buddy.blogspot.com
*/
public class Java_Process {
public static void main(String[] args) {
// Example to run "dir" in Windows
String[] command = {"cmd", "/c", "dir"};
StringBuilder cmdReturn = new StringBuilder();
try {
Process process = Runtime.getRuntime().exec(command);
try (InputStream inputStream = process.getInputStream()) {
int c;
while ((c = inputStream.read()) != -1) {
cmdReturn.append((char) c);
}
}
System.out.println(cmdReturn.toString());
} catch (IOException ex) {
Logger.getLogger(Java_Process.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPx3GZvRsZ-HPxzmLJoIwCs5tiXG8Ftf2tJ58p4Td1ceMgo5MpyZrThJUgGJMi1P4TrhbpnSvsOm4mRYkwNEySWSgMrk4Ns8LJAIkSu5v87sedVVXmXsGydFEsrfq1WWGeCQ1HINzi2iIU/s400/exec.png) |
Runtime.getRuntime().exec() |
![](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgKldFx6scpB7AQp6A6GDBJG3KRq0_8huNme8zoMQIbUIPIwC4ySFsU719X7C3LmuFvi1WcY8eqOo_q3k4JyoaT940-e3V_1uA1eGI53sw1__9JD0asFwfxElYwpcvGssV2VTArvxAIea3j/s400/exec_cmd.png) |
"dir" in Windows' cmd prompt |
Related:
-
ProcessBuilder to create operating system processes
No comments:
Post a Comment