Java process command output

How to execute a command prompt command & view output in Java

command-prompt

The basic part is very easy. To do this, we will use the Runtime’s exec method. The code would be like:

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. This I handled by created my wrapper to read the output stream. I then latch the stream to the process and bingo! Here’s the wrapper, its getter and the actual code to get the output:

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class RuntimeExec < public StreamWrapper getStreamWrapper(InputStream is, String type)< return new StreamWrapper(is, type); > private class StreamWrapper extends Thread < InputStream is = null; String type = null; String message = null; public String getMessage() < return message; > StreamWrapper(InputStream is, String type) < this.is = is; this.type = type; > public void run() < try < BufferedReader br = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String line = null; while ( (line = br.readLine()) != null) < buffer.append(line);//.append("\n"); > message = buffer.toString(); > catch (IOException ioe) < ioe.printStackTrace(); >> > // this is where the action is public static void main(String[] args) < Runtime rt = Runtime.getRuntime(); RuntimeExec rte = new RuntimeExec(); StreamWrapper error, output; try < Process proc = rt.exec("ping localhost"); error = rte.getStreamWrapper(proc.getErrorStream(), "ERROR"); output = rte.getStreamWrapper(proc.getInputStream(), "OUTPUT"); int exitVal = 0; error.start(); output.start(); error.join(3000); output.join(3000); exitVal = proc.waitFor(); System.out.println("Output: "+output.message+"\nError: "+error.message); > catch (IOException e) < e.printStackTrace(); >catch (InterruptedException e) < e.printStackTrace(); >> >
Code language: Java (java)

Источник

Читайте также:  Java удалить все пробелы строки

Java Read Process Output

If you want to access the output, you need read from the appropriate pipe.

When the standard I/O of the new process is piped to the parent process, you can use the following methods of the Process to get the I/O streams of the new process:

OutputStream getOutputStream() InputStream getInputStream() InputStream getErrorStream():

The OutputStream returned from the getOutputStream() method is connected to the standard input stream of the new process.

Writing to this output stream will be piped to the standard input of the new process.

The InputStream returned from the getInputStream() is connected to the standard output of the new process.

To capture the standard output of the new process, you need to read from this input stream.

The InputStream returned from the getErrorStream() is connected to the standard error of the new process.

To capture the standard error of the new process, you need to read from this input stream.

You can merge the output to the standard output and standard error into one destination.

It gives the exact sequence of output and the error for easier troubleshooting issues.

You can call the redirectErrorStream(true) method of the ProcessBuilder to send the data written to standard error to the standard output.

You have options to redirect the standard I/o of a new process to other destinations such as a file, and in that case, the getOutputStream(), the getInputStream(), and getErrorStream() methods return null.

Example

The following program reads and prints the data written to the standard output stream in the pipe.

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main < public static void main(String[] args) < // Get the path of the java program that started this program String javaPath = ProcessHandle.current() .info() // w w w . de m o 2 s . co m .command().orElse(null); if (javaPath == null) < System.out.println("Could not get the java command's path."); return; > // Configure the ProcessBuilder ProcessBuilder pb = new ProcessBuilder(javaPath, "--version"); try < // Start a new java process Process p = pb.start(); // Read and print the standard output stream of the process try (BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()))) < String line; while ((line = input.readLine()) != null) < System.out.println(line); > > > catch (IOException e) < e.printStackTrace(); >> >

If you run the java command with a -version option, the output is written to the standard error. And you will not get any output again because the output will be piped to the standard error stream.

You can read from the InputStream returned from the getErrorStream() method of the Process instead of the InputStream from the getInputStream() method.

Or you can redirect the error stream to the standard output stream and keep reading from the standard output.

The following code creates a ProcessBuilder with the java -version command and redirects the error stream in the standard output:

// Configure the ProcessBuilder ProcessBuilder pb = new ProcessBuilder(javaPath, "-version") .redirectErrorStream(true);

Inherit standard I/O

A new process can also inherit the standard I/O of the parent process.

If you want to set the all I/O destinations of the new process to the same as the current process, use the inheritIO() method of the ProcessBuilder, as shown:

// Configure the ProcessBuilder inheriting parent's I/O ProcessBuilder pb = new ProcessBuilder(javaPath, "--version") .inheritIO();

The ProcessBuilder.Redirect nested class represents the source of the input and destination of the outputs of the new process created by the ProcessBuilder.

The class defined the following three constants of the ProcessBuilder.Redirect type:

  • ProcessBuilder.Redirect DISCARD: Discards the outputs of the new process.
  • ProcessBuilder.Redirect.INHERIT: Indicates that the input source or output destination of the new process will be the same as that of the current process.
  • ProcessBuilder.Redirect.PIPE: Indicates that the new process will be connected to the current process over a pipe, which is the default.

You can redirect the input and outputs of the new process to a file using the following methods of the Process.Redirect class:

ProcessBuilder.Redirect appendTo(File file) ProcessBuilder.Redirect from(File file) ProcessBuilder.Redirect to(File file)

To let the new process have the same standard I/O as the current process we can use redirect method:

// Configure the ProcessBuilder inheriting parent's I/O ProcessBuilder pb = new ProcessBuilder(javaPath, "--version") .redirectInput(ProcessBuilder.Redirect.INHERIT) .redirectOutput(ProcessBuilder.Redirect.INHERIT) .redirectError(ProcessBuilder.Redirect.INHERIT);

The following code redirects the standard output of the new process to a file named java.txt in the current directory.

// Configure the ProcessBuilder ProcessBuilder pb = new ProcessBuilder(javaPath, "--version") .redirectOutput(ProcessBuilder.Redirect.to( new File("java.txt")));

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Оцените статью