Get output from process java

Get output from process java

The ProcessBuilder.start() and Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process. The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream() , getInputStream() , and getErrorStream() . The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock. Where desired, subprocess I/O can also be redirected using methods of the ProcessBuilder class. The subprocess is not killed when there are no more references to the Process object, but rather the subprocess continues executing asynchronously. There is no requirement that a process represented by a Process object execute asynchronously or concurrently with respect to the Java process that owns the Process object. As of 1.5, ProcessBuilder.start() is the preferred way to create a Process .

Читайте также:  text-align

Constructor Summary

Method Summary

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has terminated, or the specified waiting time elapses.

Methods inherited from class java.lang.Object

Constructor Detail

Process

Method Detail

getOutputStream

Returns the output stream connected to the normal input of the subprocess. Output to the stream is piped into the standard input of the process represented by this Process object. If the standard input of the subprocess has been redirected using ProcessBuilder.redirectInput then this method will return a null output stream. Implementation note: It is a good idea for the returned output stream to be buffered.

getInputStream

Returns the input stream connected to the normal output of the subprocess. The stream obtains data piped from the standard output of the process represented by this Process object. If the standard output of the subprocess has been redirected using ProcessBuilder.redirectOutput then this method will return a null input stream. Otherwise, if the standard error of the subprocess has been redirected using ProcessBuilder.redirectErrorStream then the input stream returned by this method will receive the merged standard output and the standard error of the subprocess. Implementation note: It is a good idea for the returned input stream to be buffered.

getErrorStream

Returns the input stream connected to the error output of the subprocess. The stream obtains data piped from the error output of the process represented by this Process object. If the standard error of the subprocess has been redirected using ProcessBuilder.redirectError or ProcessBuilder.redirectErrorStream then this method will return a null input stream. Implementation note: It is a good idea for the returned input stream to be buffered.

Читайте также:  Java illegal character ufeff java

waitFor

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

waitFor

public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException

Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has terminated, or the specified waiting time elapses. If the subprocess has already terminated then this method returns immediately with the value true . If the process has not terminated and the timeout value is less than, or equal to, zero, then this method returns immediately with the value false . The default implementation of this methods polls the exitValue to check if the process has terminated. Concrete implementations of this class are strongly encouraged to override this method with a more efficient implementation.

exitValue

public abstract int exitValue()

destroy

public abstract void destroy()

Kills the subprocess. Whether the subprocess represented by this Process object is forcibly terminated or not is implementation dependent.

destroyForcibly

Kills the subprocess. The subprocess represented by this Process object is forcibly terminated. The default implementation of this method invokes destroy() and so may not forcibly terminate the process. Concrete implementations of this class are strongly encouraged to override this method with a compliant implementation. Invoking this method on Process objects returned by ProcessBuilder.start() and Runtime.exec(java.lang.String) will forcibly terminate the process. Note: The subprocess may not terminate immediately. i.e. isAlive() may return true for a brief period after destroyForcibly() is called. This method may be chained to waitFor() if needed.

isAlive

Источник

Get output from a process

You will not be able to pass Java objects between processes, as they are running in different JVMs. For example: b) Make sure you are handling the process’ error stream — the process can lock up if you do not handle the error stream.

Get output from a process

  1. use public static void main (not Object as return type)
  2. Serialize the object using ObjectOutputStream (all necessary examples are in the javadoc)
  3. The only thing different from the example is the construction — construct it like ObjectOutputStream oos = new ObjectOutputStream(System.out);
  4. in the program calling exec() , get the output with process.getOutputStream()
  5. Read in an ObjectInputStream based on the already retreived OutputStream (check this)
  6. Deserialize the object (see the javadoc of ObjectInputStream)

Now, this is a weird way to do it, but as I don’t know exactly what you are trying to achieve, it sounds reasonable.

You could do System.setOut(new PrintStream(p.getOutputStream())) if you’d like to have the process print its results directly to standard output. Of course, this will override the old standard output. But you could also do other things with the process’s output stream, like have a thread that reads from it.

A problem with your code is that the main function of a class must be of type void , and will return nothing. You will not be able to pass Java objects between processes, as they are running in different JVMs. If you must do this you could serialize the object to disk, but I imagine you don’t even need to run this in a separate process.

mediaProp is a local variable in your main() method. It’s not accessible from the outside.

You’ll have to redesign your mediaProperty class a bit.

Java Runtime.getRuntime(): getting output from, However, I’m not aware of how I can get the output the command returns. Here is my code: Runtime rt = Runtime.getRuntime (); String [] commands = <"system.exe", "-send" , argument>; Process proc = rt.exec (commands); I tried doing System.out.println (proc); but that did not return anything. The execution of that command should return two Code sampleRuntime rt = Runtime.getRuntime();String[] commands = <"system.exe", "-get t">;Process proc = rt.exec(commands);BufferedReader stdInput = new BufferedReader(newInputStreamReader(proc.getInputStream()));Feedback

Get process output without blocking

Using this beautiful article and the StreamGobbler class described there (which I modified a little) I solved the problem. My implementation of StreamGobbler :

class StreamGobbler extends Thread < InputStream is; String output; StreamGobbler(InputStream is) < this.is = is; >public String getOutput() < return output; >public void run() < try < StringWriter writer = new StringWriter(); IOUtils.copy(is, writer); output = writer.toString(); >catch (IOException ioe) < ioe.printStackTrace(); >> > 
public static String runProcess(String executable, String parameter) < try < String path = String.format("%s %s", executable, parameter); Process pr = Runtime.getRuntime().exec(path); StreamGobbler errorGobbler = new StreamGobbler(pr.getErrorStream()); StreamGobbler outputGobbler = new StreamGobbler(pr.getInputStream()); // kick them off concurrently errorGobbler.start(); outputGobbler.start(); pr.waitFor(); return outputGobbler.getOutput(); >catch (Exception e) < return null; >> 

Use ProcessBuilder or Apache commons-exec.

Your posted code has bugs, this is a hard topic to get right.

Runtime — read the output from java exec, 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; …

Execute external process from java. Got the output after the process terminated, but need it before termination

There are a few things you can try to resolve your issue:

a) Make a test program and run it with your above code to ensure you can read it properly. For example:

public static void main(String[] args) < for(;;) < try < Thread.sleep(5000); System.out.println("Test output"); >catch(InterruptedException e) < // Ignore >> > 

b) Make sure you are handling the process’ error stream — the process can lock up if you do not handle the error stream. Look at this site for a tutorial on the things to avoid while using Java’s ProcessBuilder or Runtime.exec() — it includes an implementation of a StreamGobbler that will throw away all data on a stream you don’t care about.

c) Try using System.out.flush() — it may be that your output is being buffered.

EDIT: Thanks for the update. Your problem is here:

System.out.println(process.waitFor()); // Waits for the process to exit. while ((line = processReader.readLine()) != null)

If you remove the waitFor() it will keep printing until the stream closes. The stream should only close if the process dies. You should put the waitFor() after the loop?

Maybe your output does not contain a newline character, that way your while-loop won’t do anything until the process is finished.

Try it using another read method which does not wait for a newline-character, for example:

char[] cbuf = new char[10]; while(processReader.read(cbuf) != -1)

Java Process with Input/Output Stream, only exit when the reader, which reads from the process’s standard output, returns end-of-file. This only happens when the bash process exits. It will not return end-of-file if there happens at present to be no more output from the process. Instead, it will wait for the next line of output from the process and not return until it has …

Trying to execute a Java jar with Runtime.getRuntime().exec()

Use the Process instance returned by exec()

Process cat = Runtime.getRuntime().exec("java -jar C:/cat.jar C:/test.txt"); BufferedInputStream catOutput= new BufferedInputStream(cat.getInputStream()); int read = 0; byte[] output = new byte[1024]; while ((read = catOutput.read(output)) != -1)

By default, the created subprocess does not have its own terminal or console. All its standard I/O (stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream().

getInputStream() returns the input stream connected to the normal output of the subprocess.

Get process output in real time with java, I would like to print live output of a process in java; but the output is (almost) only available when the process stops execution. In other words, when I run the same process with the command line, I get more frequent feedback (output) than when I execute it with Java. I tested the following code to print the …

Источник

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