Programming Tutorials

Execute system commands in a Java Program

By: Rajan in Java Tutorials on 2006-12-11  

Most often in your Java programs you will find a need to execute system DOS commands. You can execute any system commands that are OS specific and then read the output of the system command from your Java program for further processing within the Java program.

This sample Java Program executes the 'dir' command reads the output of the dir command prints the results. This is just for understanding the concept, however, you may execute just about any command using this Runtime.getRuntime().exec() command.

import java.io.*;

public class doscmd {
    public static void main(String args[]) {
        try {
            Process p = Runtime.getRuntime().exec("cmd /c dir");
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = reader.readLine();
            while (line != null) {
                System.out.println(line);
                line = reader.readLine();
            }

        } catch (IOException e1) {
        } catch (InterruptedException e2) {
        }

        System.out.println("Done");
    }
}





Add Comment

* Required information
1000

Comments (2)

Avatar
New
Greta Pereirasays...

Hi , I want to a read file having a list of telnet commands and execute them one by one in a command prompt. This could be easier when we have lots of IP and port numbers to telnet.

How to achieve it?

Avatar
New
Normansays...

Most Viewed Articles (in Java )

Latest Articles (in Java)