Moataz Aahmed Mohammed
Moataz Aahmed Mohammed

Reputation: 1297

Run MS-DOS command from java program

How can i run MS-DOS command within my java program ?

Upvotes: 0

Views: 11511

Answers (4)

Robert
Robert

Reputation: 8609

Use a ProcessBuilder eg.

Process p = new ProcessBuilder("myCommand", "myArg").start();

This is the Java5 addition that has superseded Runtime.getRuntime().exec()

Upvotes: 3

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340743

Process p = Runtime.getRuntime().exec("cmd /C dir");
BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));

Upvotes: 3

Maxym
Maxym

Reputation: 11896

How to run command-line or execute external application from Java:

import java.io.*;

public class Main {

       public static void main(String args[]) {

            try {
                Runtime rt = Runtime.getRuntime();
                //Process pr = rt.exec("cmd /c dir");
                Process pr = rt.exec("c:\\helloworld.exe");

                BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

                String line=null;

                while((line=input.readLine()) != null) {
                    System.out.println(line);
                }

                int exitVal = pr.waitFor();
                System.out.println("Exited with error code "+exitVal);

            } catch(Exception e) {
                System.out.println(e.toString());
                e.printStackTrace();
            }
        }
}

Upvotes: 3

Vivek Goel
Vivek Goel

Reputation: 24150

use Runtime.getRuntime().exec()

Upvotes: 0

Related Questions