Press enter to see results or esc to cancel.


Run-Command-Prompt-CMD-commands-from-JAVA

This tutorial shows how to Execute Command Prompt Commands from JAVA,

Copy the below two classes to same package cmd_prompt

Now run the my_main.java as Run as Java Application
1. my_main.java
2. SyncPipe.java

1. my_main.java

package cmd_prompt;
import java.io.PrintWriter;
public class my_main {
	public static void main(String[] args) {
		String[] command =
	    {
	        "cmd",
	    };
	    Process p;
		try {
			p = Runtime.getRuntime().exec(command);
		        new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
	                new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
	                PrintWriter stdin = new PrintWriter(p.getOutputStream());
	                stdin.println("hostname");
	                stdin.close();
	                p.waitFor();
	    	} catch (Exception e) {
	 		e.printStackTrace();
		}
	}	
}	

2. SyncPipe.java

package cmd_prompt;
import java.io.InputStream;
import java.io.OutputStream;
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
      istrm_ = istrm;
      ostrm_ = ostrm;
  }
  public void run() {
      try
      {
          final byte[] buffer = new byte[1024];
          for (int length = 0; (length = istrm_.read(buffer)) != -1; )
          {
              ostrm_.write(buffer, 0, length);
          }
      }
      catch (Exception e)
      {
          e.printStackTrace();
      }
  }
  private final OutputStream ostrm_;
  private final InputStream istrm_;
}

3. The output of the Program is as shown

Download the project here 
Command_Prompt.rar

Tags