Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

Answer from kol on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - Next, we’ll spawn a new process using the .exec() method and use the StreamGobler created previously. For example, we can list all the directories inside the user’s home directory and then print it to the console:
Top answer
1 of 8
216
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

2 of 8
61

You can also watch the output like this:

final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

new Thread(new Runnable() {
    public void run() {
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;

        try {
            while ((line = input.readLine()) != null)
                System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

p.waitFor();

And don't forget, if you are running a windows command, you need to put cmd /c in front of your command.

EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:

String[] command = new String[] {
        "choice",
        "/C",
        "YN",
        "/M",
        "\"Press Y if you're cool\""
};
String inputLine = "Y";

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

writer.write(inputLine);
writer.newLine();
writer.close();

String line;

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:

Press Y if you're cool [Y,N]?Y
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this tutorial, we'll cover how to execute shell commands, bat and sh files in Java. We'll be covering examples for all exec() and ProcessBuilder approaches.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-execute-native-shell-commands-from-java-program
How to Execute Native Shell Commands from Java Program? - GeeksforGeeks
March 3, 2021 - We use a list to build commands and then execute them using the "start" method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine. ... // Run a simple Windows shell command import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ShellCommandRunner { public static void main(String[] args) { ProcessBuilder processBuilder = new ProcessBuilder(); List<String> builderList = new ArrayList<>(); // add the list of comm
🌐
Medium
beknazarsuranchiyev.medium.com › run-terminal-commands-from-java-da4be2b1dc09
Run terminal commands from Java. In this article, we will discuss how to… | by Beknazar | Medium
April 24, 2022 - In this article, we will discuss how to run terminal commands from Java code. We can execute specific commands from the terminal to execute processes in an operating system.
🌐
YouTube
youtube.com › watch
How to Execute a shell command Using Runtime.exec - Java - YouTube
In This Video, we will demonstrate how to execute a shell Command in Java using Runtime.exec function.This function provides the ability to execute a command...
Published   October 19, 2019
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands.
🌐
Stack Overflow
stackoverflow.com › questions › 16093754 › how-do-i-execute-a-sequence-of-related-console-commands
java - How do I execute a sequence of related console commands? - Stack Overflow
The basic premise revoles around the fact the dir isn't an external command but is function of cmd. I would avoid BufferedReaders when reading the output of a process as not all processes use new lines when sending output (such as progress indicators), instead you should read char for char (IMHO). You should us ProcessBuilder instead of Runtime#exec. It provides better management and allows you to redirect the error stream into the input stream, making it easier to read the input. import java.io.IOException; import java.io.InputStream; public class TestProcessBuilder { public static void main(
Find elsewhere
🌐
Blogger
javarevisited.blogspot.com › 2011 › 02 › how-to-execute-native-shell-commands.html
How to Execute Native Shell commands from Java Program? Example
How to execute native shell commands from JAVA Though it’s not recommended some time it’s become necessary to execute a native operating system or shell command from Java, especially if you are doing some kind of reporting or monitoring stuff and required information can easily be found using the native command.
🌐
CodeJava
codejava.net › java-se › file-io › execute-operating-system-commands-using-runtime-exec-methods
How to Execute Operating System Commands in Java
July 27, 2019 - For example, the following statements execute a Windows command to list content of the Program Files directory: String commandArray[] = {"cmd", "/c", "dir", "C:\\Program Files"}; Process process = Runtime.getRuntime().exec(commandArray);For other exec() methods, consult the relevant Javadoc which is listed below.
🌐
ExtraVM
thishosting.rocks › how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - Runtime.exec() is a simple high-level class, not customizable at the moment but available in every Java application. It gives the possibility for the application to communicate within its environment. The exec() method is for executing commands ...
Top answer
1 of 4
3

Couple of things that are happening incorrectly here:

  • We need to pass our command as string tokens to the exec() command
  • We need to wait for the process to exit with process.waitFor() instead of sleeping, this will block the current thread so if you don't want that you need to execute this in another thread or use an ExecutorService.
  • Advisable to check the output value of waitFor() to see if our command executed properly (value of 0) or not (any other value, typically a positive 1 in case of unsuccessful execution)
  • Optionally (to see the output) we need to redirect the standard OUT and ERR somewhere, say print it to console(), though you could put it to a file some GUI window 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 is the recommended way since JDK 1.5
  • read the inputStream

So the code will look some thing 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 this in a separate thread or using an executorService. 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();
    }
2 of 4
1

Here's a solution that uses WMIC.

public static void main( String[] args ) throws Exception {

    // Vars
    Process process;
    String output;

    // Execution
    process = Runtime.getRuntime().exec("cmd /c wmic process call create calc.exe | findstr ProcessId");
    output = readTrimmedOutput(process.getInputStream());
    System.out.println("Output from command: " + output);

    // Basic string manipulation to get process id
    String str_proc_id = output.split(" = ")[1].replace(";","");
    System.out.println("ProcessId is: " + str_proc_id);

    // Some thread delay that you can comment/uncomment for testing if running or not
    Thread.sleep(5000);

    // Finding if process is still running
    process = Runtime.getRuntime().exec("cmd /c wmic process get processid | findstr " + str_proc_id);
    output = readTrimmedOutput(process.getInputStream());

    boolean isRunning = output.contains(str_proc_id);
    System.out.println("Is process still running? " + isRunning);

}

private static String readTrimmedOutput(InputStream is) throws Exception {
    BufferedReader breader = new BufferedReader(new InputStreamReader(is));
    String line = breader.readLine();
    return line != null ? line.trim() : "";
}

Sample output

Output from command: ProcessId = 6480;
ProcessId is: 6480
Is process still running? true

For showing/displaying cmd console change some lines to:

// Execution
String your_command = "cmd.exe /c \"dir\"";
process = Runtime.getRuntime().exec("cmd /c wmic process call create \"" + your_command + "\" | findstr ProcessId");

References:

https://msdn.microsoft.com/en-us/library/aa394531(v=vs.85).aspx

https://www.computerhope.com/wmic.htm

🌐
Admfactory
admfactory.com › home › how to execute shell command from java
How to execute shell command from Java | ADMFactory
June 20, 2018 - Note: depending on your system configuration you might need permission to run a specific command. package com.admfactory.io; import java.io.BufferedReader; import java.io.InputStreamReader; public class ExecuteShellCommandExample { public static void main(String[] args) { System.out.println("Execute shell commands example"); System.out.println(); try { String cmd = "ping admfactory.com"; System.out.println("Executing command: " + cmd); Process p = Runtime.getRuntime().exec(cmd); int result = p.waitFor(); System.out.println("Process exit code: " + result); System.out.println(); System.out.println("Result:"); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } }
🌐
DZone
dzone.com › coding › languages › execute shell command from java
Execute Shell Command From Java
August 14, 2008 - String cmd = "ls -al"; Runtime run = Runtime.getRuntime(); Process pr = run.exec(cmd); pr.waitFor(); BufferedReader buf = new BufferedReader(new...
Top answer
1 of 15
166

One way to run a process from a different directory to the working directory of your Java program is to change directory and then run the process in the same command line. You can do this by getting cmd.exe to run a command line such as cd some_directory && some_program.

The following example changes to a different directory and runs dir from there. Admittedly, I could just dir that directory without needing to cd to it, but this is only an example:

Copyimport java.io.*;

public class CmdTest {
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder(
            "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            System.out.println(line);
        }
    }
}

Note also that I'm using a ProcessBuilder to run the command. Amongst other things, this allows me to redirect the process's standard error into its standard output, by calling redirectErrorStream(true). Doing so gives me only one stream to read from.

This gives me the following output on my machine:

C:\Users\Luke\StackOverflow>java CmdTest
 Volume in drive C is Windows7
 Volume Serial Number is D8F0-C934

 Directory of C:\Program Files\Microsoft SQL Server

29/07/2011  11:03    <DIR>          .
29/07/2011  11:03    <DIR>          ..
21/01/2011  20:37    <DIR>          100
21/01/2011  20:35    <DIR>          80
21/01/2011  20:35    <DIR>          90
21/01/2011  20:39    <DIR>          MSSQL10_50.SQLEXPRESS
               0 File(s)              0 bytes
               6 Dir(s)  209,496,424,448 bytes free
2 of 15
19

You can try this:-

CopyProcess p = Runtime.getRuntime().exec(command);
Top answer
1 of 1
15

I am not sure if you are asking about Shell command execution, or ipconfig in general.

If the first is the case here: Yep, you can use Runtime.getRuntime.exec(). Related Answers (In Stackoverflow):

  1. Executing shell commands from Java
  2. Want to invoke a linux shell command from Java

Moreover to the answers provided there, here is my example on how you do it with "host -t a" command for DNS lookups. I would generally recommend to read through the list you get and append them in an String for logging purposes.

p = Runtime.getRuntime().exec("host -t a " + domain);
p.waitFor();
     
BufferedReader reader = 
  new BufferedReader(new InputStreamReader(p.getInputStream()));
     
String line = "";           
while ((line = reader.readLine())!= null) {
    sb.append(line + "\n");
}

The other solution which herausuggested was to use ProcessBuilderand execute the command from there. For this you need to use Java SE 7 upwards. Here is an example that starts a process with a modified working directory and environment, and redirects standard output and error to be appended to a log file:

 ProcessBuilder pb =
   new ProcessBuilder("myCommand", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 File log = new File("log");
 pb.redirectErrorStream(true);
 pb.redirectOutput(Redirect.appendTo(log));
 Process p = pb.start();
 assert pb.redirectInput() == Redirect.PIPE;
 assert pb.redirectOutput().file() == log;
 assert p.getInputStream().read() == -1;

If you wanna know more about ProcessBuilder, read through the documentation: Oracle Documentation on Class ProcessBuilder

🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-open-command-prompt-insert-commands
Java Program to Open the Command Prompt and Insert Commands - GeeksforGeeks
April 22, 2025 - To execute the commands inside the command prompt we can use Runtime.exec() method. We can perform various commands such as dir, which is used to list all directories and the ping, which is used to test the ability of the source computer to ...
🌐
Medium
harith-sankalpa.medium.com › how-to-run-system-commands-from-java-applications-a914223edd24
How To Run System Commands From Java Applications | by Harith Sankalpa | Medium
October 21, 2019 - Note that the system command string has been split using spaces and what passes into executeCommands() method is an array of system commands and arguments. Now you have all the knowledge to launch Chrome Browser from within the Java Application.
🌐
Java-samples
java-samples.com › showtutorial.php
Execute system commands in a Java Program - Java samples
December 11, 2006 - This is just for understanding the concept, however, you may execute just about any command using this Runtime.getRuntime().exec() command.