|
JAVA现在执行外部命令,主要的方式,还是通过调用所以平台的SHELL去完成,WINDOWS下面就用CMD,LINUX或者是UNIX下面就用SHELL,下面演示一个对BAT文件的调用,并把结果回显到控制台上,其它的应用程序类。 说明: 一个调用SHELL执行外部 取得外部程序的输出流,采用适当的READER读回来,并显示出来就OK了 下面是源程序:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;
public class JavaExeBat { public JavaExeBat() { }
public static void main(String[] args) { Process p; //test.bat中的命令是ipconfig/all String cmd="c:\\test\\test.bat";
try { //执行命令 p = Runtime.getRuntime().exec(cmd); //取得命令结果的输出流 InputStream fis=p.getInputStream(); //用一个读输出流类去读 InputStreamReader isr=new InputStreamReader(fis); //用缓冲器读行 BufferedReader br=new BufferedReader(isr); String line=null; //直到读完为止 while((line=br.readLine())!=null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } }
如果如下: Windows IP Configuration Host Name . . . . . . . . . . . . : Mickey Primary Dns Suffix . . . . . . . : Node Type . . . . . . . . . . . . : Unknown IP Routing Enabled. . . . . . . . : No WINS Proxy Enabled. . . . . . . . : No DNS Suffix Search List. . . . . . : domain
Ethernet adapter 本地连接: Connection-specific DNS Suffix . : domain Description . . . . . . . . . . . : Broadcom NetXtreme Gigabit Ethernet ......
|