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

时间:2014-06-30 15:03:11

标签: java eclipse bash resources command

在我的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

2 个答案:

答案 0 :(得分:0)

使用Runtime.exec,您不必执行shell命令行,而是执行真正的可执行文件,可选地使用String [] cmdArray String的参数。 所以你不能逐行执行bat,但你可以直接用run exec执行它:

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

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

答案 1 :(得分:0)

我应该通过一个程序调用脚本的正确答案,它不能调用自己,所以我修复了它,它已经工作了:

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