Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a file using Java Runtime

I'm trying to execute a simple batch file from java using Runtime.getRuntime().exec(command); but facing issues, below is my code snippet

public class Path {
        public static void main(String args[]){
            String[] command = new String[3];
            command[0]="cmd";
            command[1]="/C";
            command[2]="D:/alt/a.bat";
    Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(
                    p.getErrorStream()));
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }
            while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

and the batch a.bat has ant -f runme.xml test in it and runme.xml resides in D:/alt physical location which has a target test, so far so good but when i try to execute the java code above, below is the ouput

D:\RCPStack\Path>ant -f runme.xml test  Buildfile: runme.xml does not
exist! Build failed

when i execute manually it works fine,seems to be the problem is with the code below is manual execution output enter image description here

how to tackle this(i don't know if the code is incorrect) and handle as a best practice

like image 379
srk Avatar asked May 29 '26 20:05

srk


1 Answers

Try to use the method Runtime.exec(String cmd, String[] envp, File dir) to set the working directory to D:/alt/.

This is because Ant must be executed in the directory where runme.xml is so Ant can find it.

like image 77
migu Avatar answered May 31 '26 10:05

migu



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!