Thursday, May 1, 2014

Invoking windows commands using java

Question: Need to invoke the windows command-prompt and run dos-commands within the same.


Answer: Here is a example that goes a a directory called D searches for a folder called "Activiti" and performs dir operation. Similar to this unix shell can be called and invoked

IDE used: Netbeans
JDK:1.7.0_51

package launchcmd;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LaunchCmd {

    public static void main(String[] args) {
      ProcessBuilder builder=new ProcessBuilder("cmd","/c","start","dir");
      builder=builder.directory(new File("D:\\Activiti"));
        try {
            builder.start();
            } catch (IOException ex) {
            Logger.getLogger(LaunchCmd.class.getName()).log(Level.SEVERE, null, ex);
                          }
        }
  }


Ouput: 

The output is as below



No comments:

Post a Comment