如何在java中执行cmd命令?

如何在java中执行cmd命令?,java,cmd,gdal,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(

我想执行这个命令

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\""});
我没有出错,但什么也没发生。 我的错误在哪里?

阅读以下内容:并一步一步地检查每个建议

流程API因gotchas而臭名昭著。

阅读以下内容:并一步一步地检查每个建议

流程API因gotchas而臭名昭著。

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

尝试检查您的返回值:

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("");
}
这只是示例代码,我没有以任何方式对其进行测试


您应该给出一些关于错误的提示。

尝试检查您的返回值:

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("");
}
这只是示例代码,我没有以任何方式对其进行测试


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

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