Run terminal commands from Java


  • The above code executes ls commands to list files and directories on my desktop. You can modify the path of the file to point to your desktop or any folder and try running other commands. If you are on a Windows machine of course you have to run the command that works on the Windows command prompt.;
if(isWindows) {
builder.command("cmd.exe", "/c", command);
}else {
builder.command("sh", "-c", command);
Process process = builder.start();
InputStream inputStream = process.getInputStream();
InputStream errorStream = process.getErrorStream();
boolean isFinished = process.waitFor(30, TimeUnit.SECONDS);
if(!isFinished) {


Runtime.getRuntime().exec(commands, null, whereToRun);
public Process exec(String[] cmdarray, String[] envp, File dir)
throws IOException {
return new ProcessBuilder(cmdarray)




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store