- Execute an external program and capture the output

王朝java/jsp·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

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

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航