Friday, October 09, 2009

menjalankan external command di 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

No comments:

Post a Comment