繁体中文
设为首页
加入收藏
当前位置:程序开发首页 >> Java >> - Execute an external program and capture the output

- Execute an external program and capture the output

2008-03-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:Execute an external program and capture the output import java.io.*; public class CmdExec { public CmdExec(String cmdline) { try { String line; Process p = Runtime.getRuntime().exec(cmdline); // j...

Execute an external program and capture the output

import java.io.*;

public class CmdExec {

public CmdExec(String cmdline) {

try {

String line;

Process p = Runtime.getRuntime().exec(cmdline);

// jdk1.0.2

DataInputStream input =

new DataInputStream(p.getInputStream());

// jdk1.1.1

// BufferedReader commandResult =

// new BufferedReader

// (new InputStreamReader(p.getInputStream()));

while ((line = input.readLine()) != null) {

System.out.println(line);

}

input.close();

}

catch (Exception err) {

System.out.println("EXEC failed: " + err.toString());

err.printStackTrace();

}

}

public static void main(String argv[]) {

/*

** javac CmdExec tree.com

** javac CmdExec "tree.com /a"

*/

new CmdExec(argv[0]);

}

}

You can include a path for the program to be executed. On the Win plateform, you will have

problem if the path contains spaces in it. To fix the problem, put the path in quotes.

public class Test {

public static void main(String[] args) throws Exception {

Process p = Runtime.getRuntime().exec(

"\"c:/program files/windows/notepad.exe\"");

p.waitFor();

}

}

责任编辑:admin
相关文章