2

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.

ITQuest
  • 113
  • 1
  • 2
  • 8
  • 1
    log1.txt will be generated in the current directory. Where is the Java program run from? – Adam Mar 17 '15 at 06:29
  • java program is there in eclipse workspace. have checked the folder containing the class file of that program. The log file is there. Thanks – ITQuest Mar 17 '15 at 06:32
  • Default current directory when launching Java apps inside eclipse is top level of project folder, not path adjacent to the .class file, try selecting project and pressing refresh (F5)... – Adam Mar 17 '15 at 06:33

1 Answers1

1
  • 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();
    }
}
Adam
  • 35,919
  • 9
  • 100
  • 137