Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute cmd commands via Java

Tags:

java

exec

I am trying to execute command line arguments via Java. For example:

// Execute command String command = "cmd /c start cmd.exe"; Process child = Runtime.getRuntime().exec(command);  // Get output stream to write from it OutputStream out = child.getOutputStream();  out.write("cd C:/ /r/n".getBytes()); out.flush(); out.write("dir /r/n".getBytes()); out.close(); 

The above opens the command line but does not execute cd or dir. Any ideas? I am running Windows XP, JRE6.

(I have revised my question to be more specific. The following answers were helpful but do not answer my question.)

like image 577
joe Avatar asked Nov 11 '10 17:11

joe


People also ask

Can you use Java in command prompt?

To compile and run a java program in command prompt follow the steps written below. open the command prompt and go to the directory where your file is saved. Make sure the Java path is set correctly.

How do I run a command prompt as administrator in Java?

Runtime. getRuntime(). exec("c:/elevate Rundll32.exe Powrprof. dll,SetSuspendState ");


2 Answers

I found this in forums.oracle.com

Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051

You need something like

   String[] command =     {         "cmd",     };     Process 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("dir c:\\ /A /Q");     // write any other commands you want here     stdin.close();     int returnCode = p.waitFor();     System.out.println("Return code = " + returnCode); 

SyncPipe Class:

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_; } 
like image 91
Pepe Avatar answered Sep 28 '22 08:09

Pepe


If you want to run several commands in the cmd shell then you can construct a single command like this:

  rt.exec("cmd /c start cmd.exe /K \"cd c:/ && dir\""); 

This page explains more.

like image 35
Vincent Ramdhanie Avatar answered Sep 28 '22 07:09

Vincent Ramdhanie