简体   繁体   中英

Runtime.exec doesn't do anything… (no errors)

I am trying to use java to run a batch file at an absolute location. The batch file will compile a couple of java files.

Here is the code which I have been trying:

String s=file.getAbsolutePath() + "\\compile.bat";
Runtime rut = Runtime.getRuntime();
try {
    rut.exec(new String[] {file.getAbsolutePath() + "\\compile.bat"});
}catch(IOException e1) {
    e1.printStackTrace();
}
System.out.println(s);

Now, when this code gets executed, I get no console errors, but the batch file is not run. When I run the batch file through Windows Explorer, however, the batch file works, compiles the files and closes when done.

How do you know that there were no console errors?

Try this:

String s=file.getAbsolutePath() + "\\compile.bat";
Runtime rut = Runtime.getRuntime();
try {
    Process process = rut.exec(new String[] {file.getAbsolutePath() + "\\compile.bat"});
    // prints out any message that are usually displayed in the console
    Scanner scanner = new Scanner(process.getInputStream());
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
}catch(IOException e1) {
    e1.printStackTrace();
}
System.out.println(s);

Check the return value of the subprocess using exitValue() . Also read the error stream getErrorStream() if the exist value is non zero.

Note that when using your invocation of Runtime.exec , the working directory of the command being executed will be the current working directory of the java process. Does your batch file need to run in a specific directory?

If you need to set a specific working directory for the sub-process, you'll need to use another version of Runtime.exec .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM