如何在java中执行cmd命令?

时间:2012-08-09 11:33:56

标签: java cmd gdal

我想执行此命令

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\""});

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

3 个答案:

答案 0 :(得分:4)

阅读本文:http://www.javaworld.com/jw-12-2000/jw-1229-traps.html并逐步完成每个建议。

Process API因陷阱而臭名昭着。

答案 1 :(得分:1)

你应该添加'/ 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\""})

答案 2 :(得分:0)

尝试检查您的返回值:

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("");
}

这只是示例代码我没有以任何方式测试它。

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

相关问题