【问题标题】:How to execute cmd command in java?如何在java中执行cmd命令?
【发布时间】:2012-08-09 19:53:48
【问题描述】:

我要执行这个命令

D:/Projects/GDAL/ogr2ogr.exe -f "MapInfo File" D:/Projects/GDAL/r/output_test.tab PG:"host=localhost user=postgres password=123456 dbname=postgis" -sql "SELECT * from filedata WHERE num=1"

我试过这个:

Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "D:/Projects/GDAL/ogr2ogr.exe -f \"MapInfo File\" D:/Projects/GDAL/r/output_test.tab PG:\"host=localhost user=postgres password=123456 dbname=postgis\" -sql \"SELECT * from filedata WHERE num=1\""});

我没有收到任何错误,但什么也没发生。 我的错在哪里?

【问题讨论】:

  • 你不是真的在使用 DOS,是吗?
  • exec 已经执行命令了吧?需要调用cmd.exe吗?
  • 我只想执行这个命令。
  • 您的引号不正确...您不能使用单引号编写字符串文字+在字符串文字内必须像这样转义双引号\" ...还可以看看@ 987654321@ ...更方便
  • 对不起,我提出了另一个 cde 行有问题。现在是正确的。但是\" 没有帮助。

标签: java cmd gdal


【解决方案1】:

阅读此内容:http://www.javaworld.com/jw-12-2000/jw-1229-traps.html 并逐步了解每个建议。

Process API 因陷阱而臭名昭著。

【讨论】:

    【解决方案2】:

    你应该添加'/C':

    Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "D:/Projects/GDAL/ogr2ogr.exe -f \"MapInfo File\" D:/Projects/GDAL/r/output_test.tab PG:\"host=localhost user=postgres password=123456 dbname=postgis\" -sql \"SELECT * from filedata WHERE num=1\""})
    

    【讨论】:

      【解决方案3】:

      尝试检查您的返回值:

      String command = ""; // Your command
      Process installproc = installcommand.execute();
      
      StringBuilder out = new StringBuilder();
      StringBuilder err = new StringBuilder();
      
      installproc.waitForProcessOutput(out, err);
      if (out.length() > 0) System.out.println("out:\n$out".toString());
      if (err.length() > 0) System.out.println("err:\n$err".toString());
      
      if(installproc.exitValue() != 0) {
      throw new Exception("");
      }
      

      这只是示例代码,我没有以任何方式对其进行测试。

      你应该给出一些关于错误是什么的提示。

      【讨论】:

        最近更新 更多