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

在java程序中运行批处理脚本,java,eclipse,bash,resources,command,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

在我的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命令行,而是执行真正的可执行文件,可以选择使用字符串[]cmdArray instad作为参数。 因此,您不能逐行执行bat,但可以使用runtime 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;

你说这是一个bash脚本,但它有一个.bat扩展名……我敢打赌你的
getResource()
调用有问题。试着打印出
executeCmd
以确保它是正确的。我没有工作,另外,我将在一个jar中交付它,它有你看到的变量我应该工作,就像我说的,bat文件必须在文件系统中,试着把它放在一个c:\tmp目录中进行测试,我将更新参数的答案。它在您的工作区中执行bat,因为您在eclipse中有一个“classes”目录。当包装在罐子里时,它将不起作用。