To run a terminal (shell) command from Java, you use the Runtime.getRuntime().exec() or ProcessBuilder classes. Both approaches launch an external process and let you read its output, errors, and exit code. ProcessBuilder is preferred for most use cases because it gives more control over working directory, environment variables, and command arguments — especially important for commands with spaces or special characters. You need a working Java Development Kit (JDK) installed and a basic understanding of your operating system’s shell syntax (e.g., ls on macOS/Linux, dir on Windows). No additional libraries are required — the Java standard library handles this natively.
What You'll Need
- A Java Development Kit (JDK) version 8 or newer installed on your machine
- A text editor or integrated development environment (IDE) like IntelliJ IDEA, Eclipse, or VS Code
- Basic familiarity with your OS command-line interface (e.g., Command Prompt, PowerShell, Terminal, or bash)
- Knowledge of the specific terminal command you want to run (e.g.,
ls -l,echo %PATH%)
Step-by-Step
- Open your Java project in your IDE or create a new one. Ensure your project is configured to use JDK 8 or higher (File > Project Structure > SDK location in IntelliJ; Project > Properties > Java Build Path in Eclipse).
- Create a new Java class (e.g.,
TerminalRunner.java). Inside themainmethod, decide whether to useRuntime.exec()orProcessBuilder. For better reliability and flexibility, chooseProcessBuilder. - Define the command as a list of strings to avoid issues with spaces or shell metacharacters. For example, to list files on Linux/macOS, use
Arrays.asList("ls", "-l"). On Windows, useArrays.asList("cmd", "/c", "dir")(never pass the full command as a single string with spaces — it breaks on arguments containing spaces). - Instantiate
ProcessBuilderwith your command list. Set the working directory if needed:builder.directory(new File("/path/to/dir"));. - Start the process:
Process process = builder.start();. - Read the command’s standard output using the process’s input stream. Wrap it in a try-with-resources block with a
BufferedReaderto safely close the stream:try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} - Read the standard error stream similarly using
process.getErrorStream(). This helps diagnose failures (e.g., "command not found"). - Wait for the process to finish and capture the exit code:
int exitCode = process.waitFor();. An exit code of 0 usually means success; non-zero indicates an error. - Close the process’s output stream (optional but good practice):
process.getOutputStream().close();— only needed if you plan to write input to the process (e.g., piping data).
Common Mistakes
- Passing the full command as a single string: e.g.,
Runtime.getRuntime().exec("ls -l /home"). This fails on Windows or with complex arguments because the JVM doesn’t parse shell syntax — it splits on spaces only. Always use an array or list of arguments. - Not consuming both stdout and stderr: If the process produces a lot of error output and you ignore it, the process may hang indefinitely waiting for its error buffer to be drained. Always read both streams — even if you just discard them.
- Ignoring the exit code: Assuming success because the process started. Always call
waitFor()and check the exit code before proceeding. - Using platform-specific commands without checking OS: e.g.,
lsdoesn’t exist on Windows. Detect the OS withSystem.getProperty("os.name")and branch logic accordingly. - Hard-coding paths: e.g.,
/bin/bashis wrong on Windows. Preferbashif it’s in thePATH, or use platform detection to callcmd.exe /corpwsh(PowerShell Core) where appropriate.
Tips
- Use
ProcessBuilder.inheritIO()for simple cases where you want the child process’s I/O to go directly to your Java process’s console — this avoids manual stream handling but gives less control. - For complex commands (e.g., pipes, redirection), shell-escape arguments or wrap the command in a shell:
Arrays.asList("sh", "-c", "ls -l | grep txt"). But only do this if necessary — it reintroduces injection risks if arguments contain user input. - Handle
IOExceptionandInterruptedExceptionproperly. ForInterruptedException, restore the interrupted status withThread.currentThread().interrupt(). - Set timeouts:
process.waitFor(10, TimeUnit.SECONDS)prevents hanging forever. If the timeout elapses, callprocess.destroyForcibly(). - Sanitize user input used in commands. Never pass untrusted strings directly — use argument lists and avoid shell interpretation.
Troubleshooting
If your command fails to run or hangs:
- Check the exit code and stderr: Re-run your code and log both output streams. If you see "'ls' is not recognized as an internal or external command", you’re likely on Windows and used a Unix command. Switch to
diror use WSL. - Verify the command exists: Open your terminal manually and run the command. If it fails there, fix your PATH or install the tool first.
- Ensure the working directory is correct: Use
builder.directory()to point to a known folder. Some commands (e.g.,git status) require being in a repository. - Test with a simple command: Try
echo "hello"first. If that works, the issue is with your specific command or its arguments. - Check for quoting issues: If using
sh -c, remember the shell interprets quotes. Escape or avoid user input in the command string. - Handle blocking streams: If the process hangs, it’s likely because stdout or stderr is full and not being read. Use separate threads or
inheritIO()to prevent blocking. - On Windows, avoid CMD-specific syntax: Commands like
copyordelare internal to CMD. Usecmd /cexplicitly:Arrays.asList("cmd", "/c", "copy", "a.txt", "b.txt").
Frequently Asked Questions
Can I run any terminal command from Java?
Yes, as long as the command is available in the system’s PATH and the user running the Java process has permission to execute it. Graphical commands (e.g., opening a browser window) may require a desktop environment and may not work in headless environments like servers.Is Runtime.exec() safe to use?
It’s safe if you avoid shell interpretation. Use the array/list form and never concatenate user input into a single command string.ProcessBuilder is safer because it enforces argument separation by design.
How do I capture output without printing to the console?
Read the streams into aStringBuilder instead of printing lines. For example: StringBuilder output = new StringBuilder(); try (BufferedReader reader = ...) { while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } }.
Why does my command work in the terminal but not in Java?
Common reasons: different PATH (Java inherits the environment, but IDEs sometimes run with modified environments), wrong working directory, or missing environment variables (e.g.,HOME). Use builder.environment() to inspect or modify variables.
Can I run multiple commands in sequence (e.g., with &&)?
Only if you invoke a shell explicitly:Arrays.asList("sh", "-c", "cmd1 && cmd2"). But avoid this unless necessary — run commands separately and check exit codes instead for better error handling.
Does this work on Android?
No. Android uses its own runtime and doesn’t provide access to a POSIX shell for arbitrary commands. Use Java’s standard APIs (e.g.,File, ProcessBuilder is restricted) or the Android NDK for native code — but only with explicit permission and caution.