Friday, November 28, 2008

Java code to execute a command etc

Java code to execute a command and enter input to that command and view output of that command.


import java.io.*;

public class CommandInput {
public static void main(String args[]) throws Exception{
String cmd = "java HelloWorld";
String passwd = "P@ssw0rd";
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
(new ConsolePrint(p.getInputStream())).start();
(new ConsolePrint(p.getErrorStream())).start();
BufferedWriter commandWriter = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
commandWriter.write(passwd);
commandWriter.close();
}
}

class ConsolePrint extends Thread{
InputStream is ;
ConsolePrint(InputStream is){
this.is = is;
}
public void run(){
BufferedReader br = new BufferedReader (new InputStreamReader(is));
String line = "";
try{
while ((line=br.readLine())!=null) {
System.out.println(line);
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}