我想达到的目的是在java中调用cmd 并打开我写好编译好的helloworld.exe(输出结果为“Hello World!”).这一点我做到了
try {
Process child = Runtime.getRuntime().exec("cmd.exe /c start "+filename);
}catch (Exception e) {
e.printStackTrace();
}
接下来就是要读取运行结果,就是读取helloworld.exe的屏幕输出,我在google上寻觅了很久没有什么头绪 请各位朋友指点下
try {
Process child = Runtime.getRuntime().exec("cmd.exe /c start "+filename);
}catch (Exception e) {
e.printStackTrace();
}
接下来就是要读取运行结果,就是读取helloworld.exe的屏幕输出,我在google上寻觅了很久没有什么头绪 请各位朋友指点下
/**
* @param command
* 要执行的命令行命令,例如cmd /c dir c:
* @param workingPath
* 要执行命令的目录,例如d:\\
* @return 命令执行产生的输出,如果执行过程中产生异常则返回异常信息
* @throws IOException
* 抛出IOException
*/
public static String runProcess(String command, String workingPath)
throws IOException
{
String result = "";
Runtime r = null;
Process p = null;
DataInputStream dis = null;
try
{
r = Runtime.getRuntime();
p = r.exec(command, null, new File(workingPath));
dis = new DataInputStream(p.getInputStream());
byte buf[] = new byte[512];
int readed = 0;
while ((readed = dis.read(buf)) > -1)
{
result += new String(buf, 0, readed, "GBK");
}
} catch (Exception e)
{
if (e instanceof IOException)
{
throw (IOException) e;
}
e.printStackTrace();
}
finally
{
dis.close();
p.destroy();
}
return result;
}
String re=runProcess("cmd start","d:/wwwrrot/image/hello.exe");