Home > Uncategorized > Running external command from java

Running external command from java

import java.io.*;

public class ExternalCommand
{
public static void main(String args[]) throws Exception
{
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;

// launch EXE and grab stdin/stdout and stderr
Process process = Runtime.getRuntime ().exec ("bc");
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();

// "write" the parms into stdin
line = "13*3" + "\n";
stdin.write(line.getBytes() );
stdin.flush();

stdin.close();

// clean up if any output in stdout
BufferedReader brCleanUp =
new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
System.out.println ("[Stdout] " + line);
}
brCleanUp.close();

// clean up if any output in stderr
brCleanUp =
new BufferedReader (new InputStreamReader (stderr));
while ((line = brCleanUp.readLine ()) != null) {
System.out.println ("[Stderr] " + line);
}
brCleanUp.close();

}
}

ref: http://www.rgagnon.com/javadetails/java-0014.html

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: