`

java调用window的cmd的ping指令

阅读更多
/k 指keep 不会结束cmd进程而会继续等输入/c 指close 执行完即结束故cmdText改为:String cmdText="cmd.exe /c start ping  "+strIpName; 另外好像直接写cmdText = "ping "+strIpName不行吗?ping是外部命令好像不用非用cmd起吧。 -------------------------------------------
import java.io.InputStream;
public class Ping { 
   public static void main(String[] args) throws Exception {       Runtime run = Runtime.getRuntime();  
String cmdText = "ping  127.0.0.1";  
Process process = run.exec(cmdText);  
process.waitFor();  
byte[] buffer = new byte[256];  
int cnt = 0;  
InputStream is = process.getInputStream();  
while((cnt=is.read(buffer))>=0) {   
System.out.print(new String(buffer,0,cnt));  
} 
}}

测试可行-----------------------
正在 Ping 127.0.0.1 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128
127.0.0.1 的 Ping 统计信息:    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),往返行程的估计时间(以毫秒为单位):    最短 = 0ms,最长 = 0ms,平均 = 0ms



import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CallCmd {	
public static void main(String[] args) {		
BufferedReader br = null;		
try {			
Process p = Runtime.getRuntime().exec("ping 127.0.0.1");	
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;			
StringBuilder sb=new StringBuilder();			
while ((line = br.readLine()) != null) {				sb.append(line+"\n");			
}		
System.out.println(sb.toString());		
} catch (Exception e) {			
e.printStackTrace();		
} finally {			
if (br != null) {				
try {					
br.close();				
} catch (Exception e) {					e.printStackTrace();				
}			
}		
}	
}}
分享到:
评论
1 楼 awaterway 2013-06-25  
正好要用。哈哈哈哈。。

相关推荐

Global site tag (gtag.js) - Google Analytics