Chinaunix首页 | 论坛 | 博客
  • 博客访问: 26278183
  • 博文数量: 2065
  • 博客积分: 10377
  • 博客等级: 上将
  • 技术积分: 21525
  • 用 户 组: 普通用户
  • 注册时间: 2008-11-04 17:50
文章分类

全部博文(2065)

文章存档

2012年(2)

2011年(19)

2010年(1160)

2009年(969)

2008年(153)

分类: Java

2008-11-14 22:00:11

如果想用JAVA来调用系统的一些命令如何办呢?
1.将结果保存到一个字符串中看代码:
package com.first;
import java.io.*;
public class DT {
      public static void main(String[] args) throws IOException
      {
      String command="ipconfig";//系统命令哦
      Runtime r=Runtime.getRuntime();
      Process p=r.exec(command);
      BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
      StringBuffer sb=new StringBuffer();
      String inline;
      while(null!=(inline=br.readLine())){
      sb.append(inline).append("\n");
      }
      System.out.println(sb.toString());
      }
}
这样的话可以得到如下的结果哦:


Windows IP Configuration





Ethernet adapter VMware Network Adapter VMnet8:



   Connection-specific DNS Suffix  . :

   IP Address. . . . . . . . . . . . : 192.168.79.1

   Subnet Mask . . . . . . . . . . . : 255.255.255.0

   Default Gateway . . . . . . . . . :



Ethernet adapter VMware Network Adapter VMnet1:



   Connection-specific DNS Suffix  . :

   IP Address. . . . . . . . . . . . : 192.168.23.1

   Subnet Mask . . . . . . . . . . . : 255.255.255.0

   Default Gateway . . . . . . . . . :



Ethernet adapter 本地连接:



   Connection-specific DNS Suffix  . :

   IP Address. . . . . . . . . . . . : 192.168.100.12

   Subnet Mask . . . . . . . . . . . : 255.255.255.0

   Default Gateway . . . . . . . . . : 192.168.100.250
看到了吧:其实是与输入命令效果是一样的哦呵呵!
当然我们也可以保存到一个文件里面去哦!
看代码:
package com.first;
import java.io.*;
public class DT {

  public static void main(String[] args) throws IOException
  {
  String filename="out.txt";
  if(args.length>0){
  filename=args[0];
  }
  String command="cmd /C dir";
  Runtime r=Runtime.getRuntime();
  Process p=r.exec(command);
  BufferedReader br=new BufferedReader(new InputStreamReader(p.getInputStream()));
  PrintStream ps=new PrintStream(new FileOutputStream(filename));
  String inline;
  while(null!=(inline=br.readLine())){
  ps.println(inline);
  }
  System.out.println("a command result has been readed to a file "+filename);
  }
}
其实就是将 是将结果保存到一个文件里面去了呵呵。
好了,以后就可以直接调用系统命令来实现一些功能了!
有时间做一个接口。方便大家调用:


阅读(1164) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~