如何在java中执行cmd命令?
问题描述:
我想执行这个命令如何在java中执行cmd命令?
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\""});
我没有错误,但什么也没有发生。 我的错误在哪里?
答
您应该添加 '/ 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\""})
+0
谢谢,它的工作。 – 2012-08-09 11:56:26
答
阅读:http://www.javaworld.com/jw-12-2000/jw-1229-traps.html并逐步完成每个建议。
Process API臭名昭着。
+0
谢谢你的这篇文章。 – 2012-08-09 11:57:04
答
尝试检查返回值:
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,是吗? – 2012-08-09 11:36:24
是的,我的坏。 Cmd命令 – 2012-08-09 11:38:41
exec已经执行了这个命令吗?你需要调用cmd.exe吗? – 2012-08-09 11:39:46