How do I run a batch file from my Java Application

2018-12-31 03:32发布

In my Java application, I want to run a batch file that calls "scons -Q implicit-deps-changed build\file_load_type export\file_load_type"

It seems that I can't even get my batch file to execute. I'm out of ideas.

This is what I have in Java:

Runtime.
   getRuntime().
   exec("build.bat", null, new File("."));

Previously, I had a Python Sconscript file that I wanted to run but since that didn't work I decided I would call the script via a batch file but that method has not been successful as of yet.

11条回答
高级女魔头
2楼-- · 2018-12-31 04:22
Process p = Runtime.getRuntime().exec( 
  new String[]{"cmd", "/C", "orgreg.bat"},
  null, 
  new File("D://TEST//home//libs//"));

tested with jdk1.5 and jdk1.6

This was working fine for me, hope it helps others too. to get this i have struggled more days. :(

查看更多
不再属于我。
3楼-- · 2018-12-31 04:26

Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:

try{    
    Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
    p.waitFor();

}catch( IOException ex ){
    //Validate the case the file can't be accesed (not enought permissions)

}catch( InterruptedException ex ){
    //Validate the case the process is being stopped by some external situation     

}

This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.

查看更多
只若初见
4楼-- · 2018-12-31 04:26

To run batch files using java if that's you're talking about...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

This should do it.

查看更多
公子世无双
5楼-- · 2018-12-31 04:27

ProcessBuilder is the Java 5/6 way to run external processes.

查看更多
旧人旧事旧时光
6楼-- · 2018-12-31 04:28

The following is working fine:

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);
查看更多
登录 后发表回答