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 › 751548 › java › Execute-Linux-Command-Return-Output
Execute Linux Command and Return Output (Java in General forum at Coderanch)
May 9, 2022 - When working with Process, you must process the output. Otherwise you run the risk of deadlock. See When Runtime.exec() won't. That's an old article, but it's still relevant. In this case the solution is two-fold: redirect the error stream so there's only one stream to read from, and then read from that stream (or discard its contents). SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Boost this thread! ... DOS command in java program question..
Discussions

How to make the output of a Java program run on command line?
ImageMagick is an executable. A simple Google search leads here: https://stackoverflow.com/questions/13991007/execute-external-program-in-java More on reddit.com
🌐 r/learnprogramming
4
1
August 30, 2019
Get output of terminal command using Java - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... For some terminal commands, they repeatedly output. For example, for something that's generating a file, it may output the percent that it is complete. I know how to call terminal commands in Java using · Process p = Runtime.getRuntim... More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
java - Collect Linux command output - Stack Overflow
Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... I am now on a linux machine. I have a Java program which would run some linux command, for example ps, top, list or free -m. ... How could I collect the output by Java program? I need to process the data in the output. ... Use Process.getInputStream... More on stackoverflow.com
🌐 stackoverflow.com
How to run Windows commands in JAVA and return the result text as a string - Stack Overflow
Possible Duplicate: Get output from a process Executing DOS commands from Java I am trying to run a cmd command from within a JAVA console program e.g.: ver and then return the output of the More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - For example, we can create a process builder for each isolated command and compose them into the pipeline: @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()))); }
🌐
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 - 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 process = Runtime.getRuntime().exec(command); // deal with OutputStream to send inputs process.getO...
🌐
Java2s
java2s.com › example › java › native-os › execute-shell-command-and-get-output.html
execute Shell Command And Get Output - Java Native OS
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Main{ public static void main(String[] argv) throws Exception{ String command = "java2s.com"; System.out.println(executeCommandAndGetOutput(command)); }//from www . j av a2s .c o m public static String executeCommandAndGetOutput(String command) throws Exception { Process proc = createAndExecuteProcess(command); logForProc(proc); return getOuputMessageOfCommand(proc.getInputStream()); } private static Process createAndExecuteProcess(String co
Find elsewhere
🌐
Viralpatel
viralpatel.net › how-to-execute-command-prompt-command-view-output-java
How to execute a command prompt command & view output in Java
May 25, 2009 - Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("ping localhost"); Code language: Java (java)The command (I’ve used “ping localhost” ) can be anything that your command prompt recognizes. It will vary on UNIX and Windows environment. Now comes the bit where you would want to see the output of the execution.
🌐
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
🌐
Reddit
reddit.com › r/learnprogramming › how to make the output of a java program run on command line?
r/learnprogramming on Reddit: How to make the output of a Java program run on command line?
August 30, 2019 -

Hi everyone,

So i have a program that basically reads from a CSV and inputs the values into a Command Line command for image making using ImageMagick. My problem is, after i read from the file and iterate a system printline with all of my commands i want to use within command prompt, i dont know how to take those and then run them all in CMD.

Ex)

The CSV: 1234, 5678, 9012

The output: C:/users/Desktop/logo "imageMagick command here + 1234" C:/users/Desktop/logofolder/1234.png

The above is essentially the command i put together with all the values substituted where the numbers are in the line. I am doing a sample size of 50. So everything is outputted correctly, i just dont know how to "run" that output in (or send it to) the command line so that the console can do that task for me (The making of the images and placing them in the folder).

The output i make in Java can literally be copy and pasted into the command line for the output i desire, but i want to do this all in essentially 1 click instead of writing it all back to a csv and then copy/pasting it all into CMD.

Thank you all for any help you may be able to give me.

I'm sorry if this is really hard to understand, im still a beginner programmer and tried my best...

🌐
Blogger
coreygoldberg.blogspot.com › 2008 › 06 › java-run-system-command-and-return.html
Corey Goldberg: Java - Run a System Command and Return Output
Run a system command and return output: import java.io.*; public static String cmdExec(String cmdLine) { String line; String output = ""; try { Process p = Runtime.getRuntime().exec(cmdLine); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { output += (line + '\n'); } input.close(); } catch (Exception ex) { ex.printStackTrace(); } return output; } Sample Usage: public static void main(String[] args) { CmdExec cmd = new CmdExec(); System.out.println(cmd.run("ls -a")); } Posted by ·
🌐
Alvin Alexander
alvinalexander.com › java › java-exec-system-command-pipeline-pipe
Java exec: How to execute a system command pipeline in Java | alvinalexander.com
That code shows you both (a) how to construct a command pipeline, (b) how to execute the command, and (c) how to get the output from that command, all using a class I wrote named SystemCommandExecutor. I'm not going to describe the SystemCommandExecutor class in this article; it's actually fairly complicated, and I described it in my "Executing system commands from Java using the ProcessBuilder and Process classes" tutorial.
🌐
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
🌐
Alvin Alexander
alvinalexander.com › java › edu › pj › pj010016
Running system commands in Java applications | alvinalexander.com
June 4, 2016 - 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. This returns a Process object. Everything else you do involves methods of the Process object. In this case, because we're running the "ps -ef" command on a Unix system, we just need to read the output of the command.
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - The Runtime class in Java is a high-level class, present in every single Java application. Through it, the application itself communicates with the environment it's in. By extracting the runtime associated with our application via the getRuntime() method, we can use the exec() method to execute ...
🌐
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 - 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.getErrorStream(); stdout = process.getInputStream(); // You could write to sdtin too but it's useless for the ls we are doing ;) line = "param1" + "n"; stdin.write(line.getBytes() ); stdin.flush(); line = "param2" + "n"; stdin.write(line.getBytes() ); stdi