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.
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.
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;
}
- use
public static void main(notObjectas return type) - Serialize the object using
ObjectOutputStream(all necessary examples are in the javadoc) - The only thing different from the example is the construction - construct it like ObjectOutputStream oos = new ObjectOutputStream(System.out);
- in the program calling
exec(), get the output withprocess.getOutputStream() - Read in an
ObjectInputStreambased on the already retreivedOutputStream(check this) - 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.
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);
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)
You don't want that call to waitFor() since it waits until the process is destroyed. You also don't want to read for as long as the InputStream is open, since such a read would terminate only when the process is killed.
Instead, you can simply start the process, and then wait for 7 seconds. Once 7 seconds have passed, read the available data in the buffer without waiting for the stream to close:
CopyBufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
Thread.sleep(7000); //Sleep for 7 seconds
while (stdInput.ready()) { //While there's something in the buffer
//read & print - replace with a buffered read (into an array) if the output doesn't contain CR/LF
System.out.println(stdInput.readLine());
}
p.destroy(); //The buffer is now empty, kill the process.
If the process keeps printing, so stdInput.ready() always returns true you can try something like this:
CopyBufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
char[] buffer = new char[16 * 1024]; // 16 KiB buffer, change size if needed
long startedReadingAt = System.currentTimeMillis(); //When did we start reading?
while (System.currentTimeMillis() - startedReadingAt < 7000) { //While we're waiting
if (stdInput.ready()){
int charsRead = stdInput.read(buffer); //read into the buffer - don't use readLine() so we don't wait for a CR/LF
System.out.println(new String(buffer, 0, charsRead)); //print the content we've read
} else {
Thread.sleep(100); // Wait for a while before we try again
}
}
p.destroy(); //Kill the process
In this solution, instead of sleeping, the thread spends the next 7 seconds reading from the InputStream, then it closes the process.
java.io.IOException: Stream closed That is probably because you're calling temp.readLine() after p.destroy().
The problem seems to be that the process doesn't add a new line termination after the part that you want to retrieve. To fix that, you can read the output from the program in small chunks instead of line by line.
Here is an example:
Copytry(InputStream is = p.getInputStream()){
byte[] buffer = new byte[10];
String content = "";
for(int r = 0; (r = is.read(buffer))!=-1;){
content+=new String(buffer, 0, r);
if(content.equals("all content")){// check if all the necessary data was retrieved.
p.destroy();
break;
}
}
}catch(Exception e){
e.printStackTrace();
}
If you know the exact format of the program's output, a better solution will be to use a scanner.
Copytry(Scanner sc = new Scanner(p.getInputStream())){
while(sc.hasNext()){
String word = sc.next();
}
}catch(Exception e){
e.printStackTrace();
}
The example above will read the program's output one word at a time.
From your comments it seems that the problem is that the process never terminates by itself and your program never exits the while loop.
To fix that, you can use a timer to destroy the process after a period of time, here is an example:
CopyTimer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
p.destroy();
t.cancel();
t.purge();
}
}, 7000);
try(BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));){
while ((inputRead=stdInput.readLine()) != null){
...
}
}catch(Exception e){
e.printStackTrace();
}
Keep in mind that this approach will always cause stdInput.readLine() to throw an exception.
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.
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));
Using https://github.com/zeroturnaround/zt-exec
new ProcessExecutor().command("python", "script.py")
.redirectOutput(new LogOutputStream() {
@Override
protected void processLine(String line) {
...
}
})
.execute();
I've often written something like:
class StreamHandler extends Thread {
InputStream is;
Writer writer;
StreamHandler(InputStream is, Writer writer) {
super("StreamHandler");
this.is = is;
this.writer = writer;
}
@Override
public void run() {
try (InputStreamReader isr = new InputStreamReader(is)) {
char buffer[] = new char[256];
int n;
while ((n = isr.read(buffer)) > 0) {
writer.write(buffer, 0, n);
}
} catch (IOException e) {
System.err.println("StreamHandler: " + e);
}
}
}
While I've used this for capturing the output stream to my own buffer, you could simply echo to stdout in real time like:
Process process = Runtime.getRuntime().exec(...);
Writer writer = new OutputStreamWriter(System.out);
StreamHandler stdout_handler = new StreamHandler(process.getInputStream(), writer);
stdout_handler.start();
I believe you are trying to get the output from process, and for that you should get the InputStream.
InputStream is = Runtime.getRuntime().exec("ls").getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader buff = new BufferedReader (isr);
String line;
while((line = buff.readLine()) != null)
System.out.print(line);
You get the OutputStream when you want to write/ send some output to Process.
Convert the stream to string as discussed in Get an OutputStream into a String and simply use Sysrem.out.print()