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;
}
🌐
Coderanch
coderanch.com › t › 672077 › java › read-output-Runtime-getRuntime-exec
Trying to read the output of a Runtime.getRuntime().exec cmd process. (Java in General forum at Coderanch)
October 27, 2016 - I'm using the below code and the connection establishes fine but I can't see any output redirecting to java. I can see the output from the cmd box. Any assistance would be appreciated. Thanks. ... I can see the output from the cmd box. What happens if you call the rasdial command and not the cmd command? ... That looks too complicated for us who are only beginning so I shall move you. Have you read the classic article by Michael Daconta? Don't go anywhere near Runtime.exec() until you have.
Discussions

Java Runtime Exec not outputting what I expect
How do I get it to output the same as typing in "javac -help"? ... Archived post. New comments cannot be posted and votes cannot be cast. Share ... Also, java actually has a compiler API and it might make sense to use that rather than to fiddle with calling javac from within your program. ... You might have to do "cmd javac" Look at how to do Java exec for "cd" where they explain why it won't work ... I'm on a Linux computer. Runtime... More on reddit.com
🌐 r/javahelp
8
1
June 3, 2016
java - Capturing stdout when calling Runtime.exec - Stack Overflow
When experiencing networking problems on client machines, I'd like to be able to run a few command lines and email the results of them to myself. I've found Runtime.exec will allow me to execute More on stackoverflow.com
🌐 stackoverflow.com
runtime - read the output from java exec - Stack Overflow
public static void main(String[] ... pr = Runtime.getRuntime().exec("java -version"); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } pr.waitFor(); System.out.println("ok!"); in.close(); System.exit(0); } in that code i'am trying to get a java version command execute is ok, but i can't read the output it just return ... More on stackoverflow.com
🌐 stackoverflow.com
java - Printing Runtime exec() OutputStream to console - Stack Overflow
I am trying to get the OutputStream of the Process initiated by exec() to the console. How can this be done? ... import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.io.Reader; public class RuntimeTests ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › padcom › a5831bea701ef08ce944
Running a process and reading its output in Java · GitHub
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. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
O'Reilly
oreilly.com › library › view › java-cookbook › 0596001703 › ch26s03.html
Running a Program and Capturing Its Output - Java Cookbook [Book]
June 21, 2001 - But for now, you need to add a few lines of code to grab the program’s output and print it: // part of ExecDemoLs.java p = Runtime.getRuntime( ).exec(PROGRAM); // getInputStream gives an Input stream connected to // the process p's standard ...
Author   Ian F. Darwin
Published   2001
Pages   888
🌐
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 - The exec() method returns a Process object that abstracts a separate process executing the command. From the Process object we can get outputs from and send inputs to the command. The following code snippet explains the principle: String command = "command of the operating system"; Process ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-runtime-exec-method
Java Runtime exec() Method with Examples - GeeksforGeeks
October 23, 2023 - With it, you can instruct the OS to perform tasks outside the realm of Java, seamlessly integrating your application with the underlying system. So let's get into the details. Before we jump into the practical examples, let's cover some essential concepts related to the exec() method: Runtime ...
Find elsewhere
🌐
Reddit
reddit.com › r/javahelp › java runtime exec not outputting what i expect
r/javahelp on Reddit: Java Runtime Exec not outputting what I expect
June 3, 2016 - ... You might have to do "cmd javac" Look at how to do Java exec for "cd" where they explain why it won't work ... I'm on a Linux computer. Runtime.getRuntime().exec("ls -l") just works as is.
Top answer
1 of 5
70

Use getErrorStream().

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

EDIT:

You can use ProcessBuilder (and also read the documentation)

ProcessBuilder   ps=new ProcessBuilder("java.exe","-version");

//From the DOC:  Initially, this property is false, meaning that the 
//standard output and error output of a subprocess are sent to two 
//separate streams
ps.redirectErrorStream(true);

Process pr = ps.start();  

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
}
pr.waitFor();
System.out.println("ok!");

in.close();
System.exit(0);
2 of 5
11

Note that we're reading the process output line by line into our StringBuilder. Due to the try-with-resources statement we don't need to close the stream manually. The ProcessBuilder class let's us submit the program name and the number of arguments to its constructor.

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

public class ProcessOutputExample
{
    public static void main(String[] arguments) throws IOException,
            InterruptedException
    {
        System.out.println(getProcessOutput());
    }

    public static String getProcessOutput() throws IOException, InterruptedException
    {
        ProcessBuilder processBuilder = new ProcessBuilder("java",
                "-version");

        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();
        StringBuilder processOutput = new StringBuilder();

        try (BufferedReader processOutputReader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));)
        {
            String readLine;

            while ((readLine = processOutputReader.readLine()) != null)
            {
                processOutput.append(readLine + System.lineSeparator());
            }

            process.waitFor();
        }

        return processOutput.toString().trim();
    }
}

Prints:

java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
🌐
Real's HowTo
rgagnon.com › javadetails › java-0014.html
Execute an external program - Real's Java How-to
This example will capture the output (from stdio) of an external program. package com.rgagnon.howto; import java.io.*; public class Exec { public static void main(String args[]) { try { String line; Process p = Runtime.getRuntime().exec("cmd /c dir"); BufferedReader bri = new BufferedReader (new InputStreamReader(p.getInputStream())); BufferedReader bre = new BufferedReader (new InputStreamReader(p.getErrorStream())); while ((line = bri.readLine()) != null) { System.out.println(line); } bri.close(); while ((line = bre.readLine()) != null) { System.out.println(line); } bre.close(); p.waitFor(); System.out.println("Done."); } catch (Exception err) { err.printStackTrace(); } } } The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be interpreted by the shell.
🌐
Coderanch
coderanch.com › t › 425969 › java › output-Runtime-getRuntime-exec
Help for getting output of Runtime.getRuntime().exec() (Java in General forum at Coderanch)
Runtime.getRuntime().exec("cmd/c start C:/jdk1.4/BIN/javac filename.java"); . My code is like this Anyone can help me please.
🌐
GitHub
gist.github.com › gersp › 1885878
Execute system command from java and grab result into String · GitHub
Execute system command from java and grab result into String - ExecUtils.java
🌐
javaspring
javaspring.net › blog › java-runtime-exec
Java Runtime Exec: A Comprehensive Guide — javaspring.net
Standard Output (getInputStream()): This stream contains the output generated by the command. You can read this stream to get the results of the command execution.
🌐
Coderanch
coderanch.com › t › 323662 › java › Direct-Runtime-getRuntime-exec-output
How Direct Runtime.getRuntime().exec output to Console window ?? (Java in General forum at Coderanch)
October 16, 2016 - A more generic approach would be some thing like this //......... Process p = Runtime.getRuntime().exec(cmd); if(p.waitFor() != 0) System.out.println(getOutAndErrStream(p)); // private String getOutAndErrStream(Process p){ StringBuffer cmd_out = new StringBuffer(""); if(p != null){ BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); String buf = ""; try{ while((buf = is.readLine()) != null){ cmd_out.append(buf); cmd_out.append (System.getProperty"line.separator")); } is.close(); is = new BufferedReader(new InputStreamReader(p.getErrorStream())); while((buf = is.readLine()) != null){ cmd_out.append(buf); cmd_out.append("\n"); } is.close(); }catch(Exception e){ e.printStackTrace(); } } return cmd_out.toString(); }