Search code examples
javabatch-filejava-batch

java command inside batch file is not getting executed when batch file is called from main method


I am calling a batch file from the main method in the following way:

public static void main(String args[]){
        Runtime rt=Runtime.getRuntime();
        try {
            Process pr=rt.exec("D:\\test1.bat");
            pr.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The content of the batch file is as follows:

xcopy d:\a1 d:\a2
call C:\Java\jdk1.6.0_27\bin\java.exe -version >log1.txt 2>&1

Upon execution files from folder a1 are getting copied to folder a2, but the log1.txt is not getting generated. However if I double click this batch file, files are getting copied and the log1.txt is getting generated with the version of java.


Solution

    • It is likely log1.txt will be generated in the current working directory of the Java application, which is not necessary the same directory as the .bat file.
    • You mention you're using Eclipse, this sets the working directory by default, unless you've changed it, to the top level of the project directory containing the application entry point (static void main).
    • eclipse does not automatically refresh the filesystem when external changes are made - try selecting project, and File => Refresh (F5)

    • There is a overloaded version of Runtime.exec() that lets you set the working directory as the 3rd parameter..

    Example

    public static void main(String args[]) {
        Runtime rt = Runtime.getRuntime();
        try {
            Process pr = rt.exec("D:\\test1.bat", null, new File("D:\\"));
            pr.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }