简体   繁体   English

在Java程序中执行bat文件

[英]Executing bat file within Java program

How do I execute a .bat or .exe within my java program that is in a sub-folder within the main folder that holds my java program. 如何在保存我的Java程序的主文件夹的子文件夹中的Java程序中执行.bat或.exe。

Runtime.getRuntime().exec("cmd /c start example.bat");

The code above works perfectly fine when the .bat is in the same folder as the java program. 当.bat与Java程序位于同一文件夹中时,上面的代码可以很好地工作。 But if my program's .java and .class files were organized in a package (and the .bat would be in a separate folder), how would I call that bat program? 但是,如果我程序的.java和.class文件被组织在一个包中(而.bat将在单独的文件夹中),那么我将如何调用该bat程序?

If the .bat file is in a different folder you should pass its full absolute path to cmd.exe. 如果.bat文件位于其他文件夹中,则应将其完整的绝对路径传递到cmd.exe。 Also, to get the correct quoting you should use the method that takes an array as argument: 另外,为了获得正确的报价,您应该使用将数组作为参数的方法:

String[] cmd = {"cmd", "/c", "start", path};
Runtime.getRuntime().exec(cmd);

If you know the location of the .bat file relative to your .jar file, you can find it using the properties of the Class object. 如果知道.bat文件相对于.jar文件的位置,则可以使用Class对象的属性找到它。 See for example How to get the path of a running JAR file? 例如,请参见如何获取正在运行的JAR文件的路径?

在您的情况下可能不可行,但是如果将批处理文件的位置添加到执行路径中怎么办?

您可以使用example.bat的完整绝对路径或工作目录中的相对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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