繁体   English   中英

在Java程序中运行批处理脚本

[英]running batch script in java program

在我的eclipse项目中,我试图运行系统命令,我将它们收集在bash中,并将其放在我的项目文件夹中。

Java代码部分是:

public static int exportDBMainData(String DBName, String UserName,
            String Password, String FilePath) {

        // First
        String executeCmd = GraphEditor.class
                .getResource("/src/sau/se/editor/recover/semapExport.bat")
                + UserName + " " + Password + " " + DBName + " " + FilePath;
        Process runtimeProcess = null;
        try {
            runtimeProcess = Runtime.getRuntime().exec(executeCmd);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        int processComplete1 = -1;
        try {
            processComplete1 = runtimeProcess.waitFor();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        return processComplete1;
    }

当我运行应用程序时,出现该错误:

java.io.IOException: Cannot run program "nullroot": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)

我究竟做错了什么?

更新我部分解决了问题,现在我得到:

java.io.IOException: Cannot run program "file:/F:/SEMAP_PROJECT/PHASE_1/ECLIPSE_KEPLER/Workspace/SeMap_Recover1.0/bin/sau/se/editor/recover/semapExport.bat": CreateProcess error=2, The system cannot find the file specified

使用Runtime.exec,您无需执行shell命令行,而是执行真正的可执行文件,可以选择使用String的String [] cmdArray instad作为参数。 因此,您无法逐行执行bat,但是可以直接使用运行时exec来执行:

 Runtime.getRuntime().exec(new String[]{
   "c:\\program files\\...\\semapExport.bat"
   ,UserName, Password,DBName,FilePath
 });

当然,bat文件必须是真实文件,而不是jar中的资源。

我应该通过程序调用脚本的正确答案,它不能自行调用,因此我像这样修复了它,并且可以正常工作:

String executeCmd = "cmd /c start "
                + DBUtils.class
                        .getResource("/sau/se/editor/recover/semapExport.bat")
                + " " + UserName + " " + Password + " " + DBName + " "
                + FilePath;

暂无
暂无

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

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