Monday, July 21, 2014

How to execute a window command from Java

This java code will show how can we execute a windows command from Java

package commons.utilities;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ExecuteCommandFromJava {
public static void main(String[] args) throws IOException {
   String[] command = new String[3];
        command[0] = "cmd";
        command[1] = "/c";
        command[2] = "E: && dir && cd snap";
        Process p = Runtime.getRuntime().exec(command);
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String Error;
        while ((Error = stdError.readLine()) != null) {
            System.out.println(Error);
        }
        while ((Error = stdInput.readLine()) != null) {
            System.out.println(Error);
        }
}
}

No comments:

Post a Comment