【问题标题】:running batch script in java program在java程序中运行批处理脚本
【发布时间】:2014-08-21 00:05:14
【问题描述】:

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

【问题讨论】:

  • 你说它是一个 bash 脚本,但它有一个 .bat 扩展名......
  • 我敢打赌你的getResource() 电话有问题。尝试打印出executeCmd 以确保它是正确的。

标签: java eclipse bash resources command


【解决方案1】:

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

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

【讨论】:

  • 它在你的工作空间中执行bat,因为你在eclipse中有一个“classes”目录。打包在 jar 中时将无法使用。
【解决方案2】:

使用 Runtime.exec,您执行的不是 shell 命令行,而是一个真正的可执行文件,可以选择使用 String[] cmdArray instad of a String 的参数。 所以不能逐行执行bat,但是可以直接用runtime exec执行:

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

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

【讨论】:

  • 我没工作,另外,我会把它放在一个罐子里,它有你看到的变量
  • 我应该工作,就像我说的那样,bat 文件必须在文件系统中,尝试将其放在 c:\tmp 目录中进行测试,我将更新我的参数答案。
猜你喜欢
  • 1970-01-01
  • 2013-07-30
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多