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.

Answer from Senthil on Stack Overflow
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;
}
🌐
Oracle
support.oracle.com › knowledge › Oracle Database Products › 430403_1.html
How To Redirect Output From Java Callout Runtime.exec() To A File On Unix Without Using Process.getInputStream()
February 3, 2022 - Having some Java code to run an external process like · public class OSCommand{ public static String Run(String Command){ try{ Runtime.getRuntime().exec(Command); return("0"); } catch (Exception e){ System.out.println("Error running command: " + Command + "\n" + e.getMessage()); return(e.getMessage()); } } } we want to redirect the output of this process to a file.
🌐
O'Reilly
oreilly.com › library › view › java-cookbook › 0596001703 › ch26s03.html
Running a Program and Capturing Its Output - Java Cookbook [Book]
June 21, 2001 - ExecAndPrint has several overloaded forms of its run( ) method (see the documentation for details), but they all take at least a command, and optionally an output file to which the command’s output is written. Example 26-2 shows the code for some of these methods. Example 26-2. ExecAndPrint.java (partial listing) /** Need a Runtime object for any of these methods */ protected static Runtime r = Runtime.getRuntime( ); /** Run the command given as a String, printing its output to System.out */ public static ...
Author   Ian F. Darwin
Published   2001
Pages   888
🌐
Coderanch
coderanch.com › t › 327920 › java › writing-process-output-stream-getOutputStream
writing process output stream (p.getOutputStream) to a file (Java in General forum at Coderanch)
Here is the code which i am using which does not work Process p = Runtime.getRuntime().exec("java -cp some program); BufferedOutputStream o = (BufferedOutputStream) p.getOutputStream(); String str = o.toString(); if (str !=null){ byte buf[] = str.getBytes(); OutputStream os = new FileOutputStream("syndierr.txt"); os.write(buf); os.close(); } Any help will be appreciated.
🌐
Coderanch
coderanch.com › t › 564537 › java › Runtime-getRuntime-exec-cmd-work
Runtime getRuntime() exec(cmd[]) - How does this work? (Java in General forum at Coderanch)
January 15, 2012 - The structure looks correct, and since my similar /bin/ls command worked fine, and since his command works find without the -f 5, I have to guess that the -f 5 is either invalid to start with (hence my suggestion to try it directly on the command line) or else using -f 5 produces enough output on stdout or stderr to make it block. ... Jeff Verdegan wrote: No. We're not redirecting into -f 5. Those args are completely unrelated to the redirection. We're redirecting our input to come from the file specified by the "path" variable. Java doesn't know or care anything about those args or the redirection.
🌐
Coderanch
coderanch.com › t › 651624 › os › Redirect-output-sort-command-file
Redirect output of sort command to a file (GNU/Linux forum at Coderanch)
June 22, 2015 - Sharad N Srivastava wrote: Also, instead of firing multiple process from Java, I created a shell script which accepts the file name as input and does all the heavy operation like SORT/SPLIT/Logic execution and returns the result. You are still using Runtime.exec() so you are still creating a Process object so you still need to handle the Process stdout and stderr streams and you still need to handle the Process exit code.
🌐
Medium
medium.com › enekochan › run-a-command-from-a-java-application-dealing-properly-with-stdin-stdout-and-stderr-8be78063f2cf
Run a command from a Java application dealing properly with stdin, stdout and stderr | by Eneko | enekochan | Medium
November 5, 2018 - If you want to run an external command from a Java application you have to deal properly with the input, output and error file descriptors or it won’t work. The key is to read the output and error buffers. This is a simple example on how to do this: import java.io.*; public class CmdExec { public static void main(String argv[]) { try { String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; // launch the command and grab stdin/stdout and stderr Process process = Runtime.getRuntime().exec("ls -la"); stdin = process.getOutputStream(); stderr = process.getE
Find elsewhere
🌐
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 - @Test public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { List<ProcessBuilder> builders = Arrays.asList( new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), new ProcessBuilder("wc", "-l")); List<Process> processes = ProcessBuilder.startPipeline(builders); Process last = processes.get(processes.size() - 1); List<String> output = readOutput(last.getInputStream()); assertThat("Results should not be empty", output, is(not(empty()))); } In the above example, we’re searching for all the java files inside the src directory and piping the results into another process to count them. To learn about other improvements made to the Process API in Java 9, check out our great article on Java 9 Process API Improvements. As we’ve seen in this quick tutorial, we can execute a shell command in Java in two distinct ways.
🌐
GitHub
gist.github.com › padcom › a5831bea701ef08ce944
Running a process and reading its output in Java · GitHub
Save padcom/a5831bea701ef08ce944 to your computer and use it in GitHub Desktop. Download ZIP · Running a process and reading its output in Java · Raw · Execute.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Real's HowTo
rgagnon.com › javadetails › java-0014.html
Execute an external program - Real's Java How-to
Runtime.getRuntime().exec ("rundll32 SHELL32.DLL,ShellExec_RunDLL " + file.getAbsolutePath()); See also this HowTo about the new Desktop API, the recommended solution (but you need JDK1.6). See also this one to open the default browser. The following example start a Dial-up connection on the Win plateform : [Dialup.java] public class Dialup { public static void main(String[] args) throws Exception { Process p = Runtime.getRuntime() .exec("rundll32.exe rnaui.dll,RnaDial MyConnection"); p.waitFor(); System.out.println("Done."); } } The "MyConnection" is the DUN and it's case sensitive.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - The exec() function in Java's Runtime class provides various options for communicating with the operating system. Once you understand this, you can easily integrate system commands into your Java programs. Remember to choose the option that best suits your needs.
🌐
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 - Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.Basically, to execute a system command, pass the command string to the exec() method of the Runtime class.
🌐
Tabnine
tabnine.com › home › code library
https://www.tabnine.com/code/java/methods/java.lan...
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
Top answer
1 of 2
10

Because the Process will execute in a new thread it's likely that there is no output or incomplete output available when you come to your while loop.

Process p = pb.start();  
// process runs in another thread parallel to this one

BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));

// bri may be empty or incomplete.
while ((line = bri.readLine()) != null) {
    RESULT+=line;
}

So you need to wait for the process to complete before attempting to interact with it's output. Try using the Process.waitFor() method to pause the current thread until your process has had an opportunity to complete.

Process p = pb.start();  
p.waitFor();  // wait for process to finish then continue.

BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((line = bri.readLine()) != null) {
    RESULT+=line;
}

This is only a simple approach you could also process the output of the process while it runs in parallel but then you would need to monitor the status of the process i.e. is it still running or has it completed, and the availability of output.

2 of 2
7

Use Apache Commons Exec, it will make your life much easier. Check the tutorials for information about basic usage. To read the command line output after obtaining an executor object (probably DefaultExecutor), create an OutputStream to whatever stream you wish (i.e a FileOutputStream instance may be, or System.out), and:

executor.setStreamHandler(new PumpStreamHandler(yourOutputStream));