java调用bat&监控windows下的某一进程是否关闭

java调用bat&监控windows下的某一进程是否关闭


java调用bat:如果要和Runtime创建的进程交互,必须自己写交互的代码,例如通过socket,两个java进程互相通信。

Java代码 复制代码
  1. import java.io.IOException;   
  2.   
  3. public class Main {   
  4.   
  5. public static void main(String[] args){   
  6. try {   
  7. Runtime rt = Runtime.getRuntime();   
  8. rt.exec("cmd.exe /c start c:\\1.bat");   
  9. catch (IOException e) {   
  10. e.printStackTrace();   
  11. }   
  12. }   
  13. /* 1.bat的内容  
  14. * @echo off  
  15. * echo lsd>>c:\lsd.txt  
  16. *  
  17. * */  
  18. }  
import java.io.IOException;

public class Main {

public static void main(String[] args){
try {
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start c:\\1.bat");
} catch (IOException e) {
e.printStackTrace();
}
}
/* 1.bat的内容
* @echo off
* echo lsd>>c:\lsd.txt
*
* */
}
 



java监控windows下的某一进程是否关闭:应为这里直接调用的操作系统带的命令,所以可以直接用getInputStream()来获得操作系统的反馈信息。如果调用命令启动另一个java应用,两个java应用互相交互,则getInputStream()就没用了。

Java代码 复制代码
  1. ProcessBuilder pb = new ProcessBuilder("tasklist");   
  2. try {   
  3. Process p = pb.start();   
  4. BufferedReader rb = new BufferedReader(new InputStreamReader(p.getInputStream()));   
  5. String line;   
  6. String storeLine="";   
  7. while((line=rb.readLine())!=null){   
  8. if(line.indexOf("eclipse.exe")!=-1)//过滤进程eclipse.exe的信息   
  9. storeLine = line;   
  10. System.out.println(line);   
  11. }   
  12. //获取进程的pid号   
  13. if(storeLine!=""){   
  14. int beginIndex = storeLine.indexOf("exe");   
  15. int endIndex = storeLine.indexOf("Console");   
  16. String pid = storeLine.substring(beginIndex+3, endIndex).trim();   
  17. System.out.println("this process id is "+pid);   
  18. }else{   
  19. System.out.println("this process is not exist");   
  20. }   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值