Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bat file does not execute within Java

I have written some code for executing .bat file. which contains some commands like setting java classpath,etc..And finally there is one command which runs a Java class file.The HelloWorld class converts some xml file and generating a new xml file in some folder. When I double click .bat file, it executes fine, but when I try to run I am not getting any output as I was getting through double click the .bat file. How to make a batch execute and probably it would be nice if I could see the results through Java console.

Following is MyJava code to execute the .bat file

public void run2() {
        try {
            String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
            Process p = Runtime.getRuntime().exec(commands);
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

And below the some commands which has been set to .bat file

set CLASSPATH=%CLASSPATH%;C:/MyWork/Java
set CLASSPATH=%CLASSPATH%;C:/MyWork/Java/classes
java -cp test.jar;test2.jar test.HelloWorld

Tried with "/C" commad as well. It does not execute. Actually it does not give effect of double click the .bat file. Is there any other way that I can try with?

I can see the contents inside the .bat file through Eclipse console. But it does not give the desired output. Desired output means when I double click .bat file, it executes well. But through java call, I can see the contents only .

like image 397
English Learner Avatar asked Apr 12 '26 14:04

English Learner


1 Answers

When using cmd.exe use /C-Parameter to pass command:

String []commands = {"cmd.exe","/C","C:/MyWork/Java/classes/run.bat"} ;
like image 107
piet.t Avatar answered Apr 15 '26 02:04

piet.t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!