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
Answer from Luke Woodward on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - You can obtain a Runtime object using the getRuntime() method. Process: When you call exec(), it spawns a new native process. This process runs independently of your Java application and allows you to execute system commands.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ java โ€บ lang โ€บ runtime_exec.htm
Java Runtime exec() Method
package com.tutorialspoint; public class RuntimeDemo { public static void main(String[] args) { try { // print a message System.out.println("Executing notepad.exe"); // create a process and execute notepad.exe Process process = Runtime.getRuntime().exec("notepad.exe"); // print another message System.out.println("Notepad should now open."); } catch (Exception ex) { ex.printStackTrace(); } } } Let us compile and run the above program, this will produce the following result โˆ’ ยท Executing notepad.exe Notepad should now open. The following example shows the usage of Java Runtime exec() method.
Discussions

Run cmd commands through Java - Stack Overflow
You don't say how you're running your Java code (from a command prompt, from an IDE, in a web app, ...), so I can't say what you could do to fix this apparent PATH issue. 2013-03-18T22:14:25.37Z+00:00 ... @LukeWoodward - Thanks. Can you please explain what these string parameters mean - "/c" and "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir" ? I am actually trying to execute ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Running Command Line in Java - Stack Overflow
Is there a way to run this command line within a Java application? java -jar map.jar time.rel test.txt debug I can run it with command but I couldn't do it within Java. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How do I execute Command Prompt commands in Java 21.0.2
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/learnjava
4
2
May 18, 2024
Java Runtime.getRuntime(): getting output from executing a command line program - Stack Overflow
I'm using the runtime to run command prompt commands from my Java program. However, I'm not aware of how I can get the output the command returns. Here is my code: Runtime rt = Runtime.getRuntime... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
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.
๐ŸŒ
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 - In this article, weโ€™ll learn how to execute a shell command from Java applications. First, weโ€™ll use the .exec() method the Runtime class provides.
๐ŸŒ
Java Guides
javaguides.net โ€บ 2023 โ€บ 09 โ€บ java-runtimeexec.html
Java Runtime.exec()
September 27, 2023 - - The subprocess is not synchronized with the Java application, so you might want to use methods like waitFor() on the Process object to have your Java program wait for the subprocess to finish. - Be cautious while executing arbitrary commands, especially if they are derived from untrusted sources. public class ExecuteCommandExample { public static void main(String[] args) { Runtime runtime = Runtime.getRuntime(); try { // Using the first syntax: exec(String command) Process process = runtime.exec("ping -c 1 www.google.com"); // Retrieving the input stream (where the command sends its output)
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 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
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ how do i execute command prompt commands in java 21.0.2
r/learnjava on Reddit: How do I execute Command Prompt commands in Java 21.0.2
May 18, 2024 -

I tried using the following function:

Runtime.getRuntime().exec("DIR")

but it doesn't get executed and my IDE always shows the following warning:

The method exec(String) from the type Runtime is deprecated since version 18Java(67110270)

Top answer
1 of 3
3
When something is marked as deprecated it is always helpful to check out the documentation. Usually it tells you why it was deprecated but also what method to use instead. Deprecated. This method is error-prone and should not be used, the corresponding method exec(String[]) or ProcessBuilder should be used instead. The command string is broken into tokens using only whitespace characters. For an argument with an embedded space, such as a filename, this can cause problems as the token does not include the full filename. So you can either use exec(String[]) or preferably ProcessBuilder . Then, you have to actually pass the following command: ["cmd", "/c", "DIR"] because "DIR" is not a real program, but a command of the windows command prompt. But even then, it will probably still look like your program doesn't work because you won't see any output. To fix this you have to either manually read the output using Process.getInputStream() , or you can simply do var process = new ProcessBuilder("cmd", "/c", "DIR") .redirectOutput(ProcessBuilder.Redirect.INHERIT) .start(); which will redirect output to your Java's program stdout. You may need to add process.waitFor(); To make sure your main thread does not exit before your process has finished.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - To actually execute a Process, we run the start() command and assign the returned value to a Process instance.
๐ŸŒ
Real's HowTo
rgagnon.com โ€บ javadetails โ€บ java-0014.html
Execute an external program - Real's Java How-to
String fileName = "c:\\Applications\\My Documents\\test.doc"; String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName}; Runtime.getRuntime().exec(commands); // Win9x Runtime.getRuntime().exec("start myscript.vbs"); // WinNT Runtime.getRuntime().exec("cmd /c start myscript.vbs"); or // with a visible console Runtime.getRuntime().exec("cscript myscript.vbs"); // with no visible console Runtime.getRuntime().exec("wscript myscript.vbs"); Runtime.getRuntime().exec("hh.exe myhelpfile.chm"); import java.io.IOException; class StartExcel { public static void main(String args[]) throws IOException { Runtime.getRuntime().exec("cmd /c start excel.exe"); } } To load a worksheet
Top answer
1 of 14
324

Here is the way to go:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

2 of 14
88

A quicker way is this:

public static String execCmd(String cmd) throws java.io.IOException {
    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Which is basically a condensed version of this:

public static String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;
}

I know this question is old but I am posting this answer because I think this may be quicker.

Edit (For Java 7 and above)

Need to close Streams and Scanners. Using AutoCloseable for neat code:

public static String execCmd(String cmd) {
    String result = null;
    try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
            Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
        result = s.hasNext() ? s.next() : null;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}
๐ŸŒ
Coderanch
coderanch.com โ€บ t โ€บ 641832 โ€บ java โ€บ execute-cmd-command-Runtime-getRuntime
Trying to execute a cmd command using Runtime.getRuntime().exec [Solved] (Beginning Java forum at Coderanch)
two dos commands. Can you reply with array of CmdArray? ... You'll either have to execute Runtime.exec() twice (once for each command) or put the two commands in a script and run the script. Fair warning: it's not safe to simply say "execute ping". That makes assumptions about your runtime environment that may not always be true.
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ java-runtime-exec
Java Runtime Exec: A Comprehensive Guide โ€” javaspring.net
In Java, the Runtime.getRuntime().exec() method provides a powerful way to execute system commands from within a Java application. This feature allows Java programs to interact with the underlying operating system, running external processes ...
๐ŸŒ
Alvin Alexander
alvinalexander.com โ€บ java โ€บ edu โ€บ pj โ€บ pj010016
Running system commands in Java applications | alvinalexander.com
June 4, 2016 - The first thing you do is specify the command you want to run by supplying this command to the Runtime class. Because you can't create your own instance of the Runtime class, you first use the getRuntime method to access the current runtime environment and then invoke the Runtime exec method.
๐ŸŒ
Oracle
docs.oracle.com โ€บ javase โ€บ 7 โ€บ docs โ€บ api โ€บ java โ€บ lang โ€บ Runtime.html
Runtime (Java Platform SE 7 )
Executes the specified command and arguments in a separate process with the specified environment and working directory.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ problem with runtime.exec() method and using multiple commands in linux
r/javahelp on Reddit: Problem with Runtime.exec() method and using multiple commands in Linux
September 16, 2019 -

I am new to both Java and Linux, I was trying to use some Runtime.exec() commands that would allow my program to execute commands in Linux such as cd /mnt/ and ls --group-directories-first to list files and directories contained in /mnt/ but I think I am making a problem with the execution.

I tried my code to only include the ls --group-directories-first and it worked like a charm, only problem was, it only listed subdirectories and files in the projects folder. I wanted to make my program go to /mnt/ first so I made my command line to a command array by using exec(String[] cmdarray) format as p = Runtime.getRuntime().exec(new String[]{"cd /mnt/","ls --group-directories-first"}); and when I ran it on linux, it just got executed without any error but also without any feedback/printed lines.

Here is my code:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class linCom {
    public static void main(String args[]) {
        String s;
        Process p;

        try {
            p = Runtime.getRuntime().exec("ls --group-directories-first");
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}


    }
}

This worked and printed out:

line: DummyFolder1

line: linCom.class

line: linCom.java

exit: 0

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class linCom {
    public static void main(String args[]) {
        String s;
        Process p;

        try {
            p = Runtime.getRuntime().exec(new String[]{"cd /mnt/","ls --group-directories-first"});
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            while ((s = br.readLine()) != null)
                System.out.println("line: " + s);
            p.waitFor();
            System.out.println ("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {}


    }
}

This just got executed with no errors but also no prints on the screen.

I expected my program to just go to the /mnt/ directory and print out subdirectories and files on there, but it just got executed with no errors and no printed lines.

I have looked at other entries but could not find any answer to my problem.

๐ŸŒ
IBM
ibm.com โ€บ docs โ€บ ssw_ibm_i_73 โ€บ rzaha โ€บ javalang.htm
Using java.lang.Runtime.exec()
Use the java.lang.Runtime.exec() method to call programs or commands from within your Java program. Using java.lang.Runtime.exec() method creates one or more additional thread-enabled jobs. The additional jobs process the command string that you pass on the method.
๐ŸŒ
GitHub
gist.github.com โ€บ f3348e7843994bdd56f0
Java Runtime.getRuntime().exec() Example ยท GitHub
package api; import java.io.Bu... import java.io.InputStreamReader; public class Exec { /** * @param args */ public static void main(String[] args) { String result = ""; try { // Execute command String command = "k:\\curl.exe -d login_name=mohwtest -d login_passwd=12345 --insecure https://mohw.cyberhood.net.tw/xml_import.php"; Process child = Runtime.getRuntim...
๐ŸŒ
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.