[java] How to open the command prompt and insert commands using Java?

Is it possible to open the command prompt (and I guess any other terminal for other systems), and execute commands in the newly opened window?

Currently what I have is this:

Runtime rt = Runtime.getRuntime();
rt.exec(new String[]{"cmd.exe","/c","start"});

I've tried adding the next command after the "start", I've tried running another rt.exec containing my command, but I can't find a way to make it work.

If it matters, I'm trying to run a command similar to this:

java -flag -flag -cp terminal-based-program.jar

EDIT Unfortunately I have had some strange findings. I've been able to successfully launch the command prompt and pass a command using this:

rt.exec("cmd.exe /c start command");

However, it only seems to work with one command. Because, if I try to use the command separator like this, "cmd.exe /c start command&command2", the second command is passed through the background (the way it would if I just used rt.exec("command2");). Now the problem here is, I realized that I need to change the directory the command prompt is running in, because if I just use the full path to the jar file, the jar file incorrectly reads the data from the command prompt's active directory, not the jar's directory which contains its resources.

This question is related to java command terminal launch

The answer is


If you are running two commands at once just to change the directory the command prompt runs in, there is an overload for the Runtime.exec method that lets you specify the current working directory. Like,

Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start command", null, new File(newDir));

This will open command prompt in the directory at newDir. I think your solution works as well, but this keeps your command string or array a little cleaner.

There is an overload for having the command as a string and having the command as a String array.

You may find it even easier, though, to use the ProcessBuilder, which has a directory method to set your current working directory.

Hope this helps.


public static void main(String[] args) {
    try {
        String ss = null;
        Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
        BufferedWriter writeer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
        writeer.write("dir");
        writeer.flush();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        System.out.println("Here is the standard output of the command:\n");
        while ((ss = stdInput.readLine()) != null) {
            System.out.println(ss);
        }
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((ss = stdError.readLine()) != null) {
            System.out.println(ss);
        }

    } catch (IOException e) {
        System.out.println("FROM CATCH" + e.toString());
    }

}

You have to set all \" (quotes) carefully. The parameter \k is used to leave the command prompt open after the execution.

1) to combine 2 commands use (for example pause and ipconfig)

Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"pause && ipconfig\"", null, selectedFile.getParentFile());

2) to show the content of a file use (MORE is a command line viewer on Windows)

File selectedFile = new File(pathToFile):
Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"MORE \"" + selectedFile.getName() + "\"\"", null, selectedFile.getParentFile());

One nesting quote \" is for the command and the file name, the second quote \" is for the filename itself, for spaces etc. in the name particularly.


Please, place your command in a parameter like the mentioned below.

Runtime.getRuntime().exec("cmd.exe /c start cmd /k \" parameter \"");

The following works for me on Snow Leopard:

Runtime rt = Runtime.getRuntime();
String[] testArgs = {"touch", "TEST"};
rt.exec(testArgs);

Thing is, if you want to read the output of that command, you need to read the input stream of the process. For instance,

Process pr = rt.exec(arguments);
BufferedReader r = new BufferedReader(new InputStreamReader(pr.getInputStream()));

Allows you to read the line-by-line output of the command pretty easily.

The problem might also be that MS-DOS does not interpret your order of arguments to mean "start a new command prompt". Your array should probably be:

{"start", "cmd.exe", "\c"}

To open commands in the new command prompt, you'd have to use the Process reference. But I'm not sure why you'd want to do that when you can just use exec, as the person before me commented.


String[] command = {"cmd.exe" , "/c", "start" , "cmd.exe" , "/k" , "\" dir && ipconfig 
\"" };
ProcessBuilder probuilder = new ProcessBuilder( command );
probuilder.directory(new File("D:\\Folder1"));
Process process = probuilder.start();

You can use any on process for dynamic path on command prompt

Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\rakhee\\Obligation Extractions\" && dir");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\oxyzen-workspace\\BrightleafDesktop\\Obligation Extractions\" && dir");

You just need to append your command after start in the string that you are passing.

String command = "cmd.exe /c start "+"*your command*";

Process child = Runtime.getRuntime().exec(command);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to command

'ls' is not recognized as an internal or external command, operable program or batch file Command to run a .bat file how to run python files in windows command prompt? Run a command shell in jenkins How to recover the deleted files using "rm -R" command in linux server? Split text file into smaller multiple text file using command line ansible : how to pass multiple commands Jmeter - Run .jmx file through command line and get the summary report in a excel cocoapods - 'pod install' takes forever Daemon not running. Starting it now on port 5037

Examples related to terminal

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) Can't compile C program on a Mac after upgrade to Mojave Flutter command not found VSCode Change Default Terminal How to switch Python versions in Terminal? How to open the terminal in Atom? Color theme for VS Code integrated terminal How to edit a text file in my terminal How to open google chrome from terminal? Switch between python 2.7 and python 3.5 on Mac OS X

Examples related to launch

How to open the command prompt and insert commands using Java? Android Respond To URL in Intent