Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java application to execute commands in command prompt [closed]

Tags:

java

command

I would like to know, is there a way to let a java application open command prompt (cmd.exe) and type/execute commands, preferably without the user seeing the command prompt window.

If anyone knows a sample application or a piece of code that can do this, your answer will be appreciated!

like image 767
Mdlc Avatar asked Dec 07 '22 07:12

Mdlc


2 Answers

The java.lang.ProcessBuilder and java.lang.Process classes are available for executing and communicating with external programs. With an instance of the java.lang.ProcessBuilder class, it can execute an external program and return an instance of a subclass of java.lang.Process. The class Process provides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.

public class ProcessBuildDemo { 
    public static void main(String [] args) throws IOException {

        String[] command = {"CMD", "/C", "dir"};
        ProcessBuilder probuilder = new ProcessBuilder( command );
        //You can set up your work directory
        probuilder.directory(new File("c:\\xyzwsdemo"));

        Process process = probuilder.start();

        //Read out dir output
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        System.out.printf("Output of running %s is:\n",
                Arrays.toString(command));
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        //Wait to get exit value
        try {
            int exitValue = process.waitFor();
            System.out.println("\n\nExit Value is " + exitValue);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
like image 165
Juned Ahsan Avatar answered Dec 15 '22 00:12

Juned Ahsan


use below code to execute process using java.

final List<String> commands = new ArrayList<String>();                
    commands.add("cmd");
    commands.add(input2); // second commandline argument 
    commands.add(input3);// third commandline agrument
    ProcessBuilder pb = new ProcessBuilder(commands);
like image 44
Alpesh Gediya Avatar answered Dec 14 '22 22:12

Alpesh Gediya