Rakesh
Rakesh

Reputation: 91

Not able to execute command from java

I want to execute below command from java program .

java -jar jarfile.jar -dir C:/MyDirectory -out C:/MyDirectory/example.html

I tried following , but its opening cmd prompt , but it not executing next command

Runtime rt = Runtime.getRuntime();
    try {
        rt.exec(new String[] { "cmd.exe", "/c", "start" , "java -jar exampleJar.jar -dir C:\\MyDirectory -out C:\\MyDirectory\\exampleHtml.html" });

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Upvotes: 0

Views: 108

Answers (1)

SSH
SSH

Reputation: 1627

I am using the following piece of code and its working perfect,ProcessBuilder is used to create operating system processes and each instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. To create new subprocesses with the same instance start() method can be called repeatedly.

public void execute(String[] code){

        try{
            ProcessBuilder pb=new ProcessBuilder(code);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            while(inStreamReader.readLine() != null){
                System.out.println(inStreamReader.readLine());
            }
        } catch (IOException e) {
            System.out.println(e.toString());
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }

Upvotes: 2

Related Questions