`
javaG
  • 浏览: 549856 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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

    博客分类:
  • java
阅读更多


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

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()就没用了。

ProcessBuilder pb = new ProcessBuilder("tasklist");
try {
Process p = pb.start();
BufferedReader rb = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
String storeLine="";
while((line=rb.readLine())!=null){
if(line.indexOf("eclipse.exe")!=-1)//过滤进程eclipse.exe的信息
storeLine = line;
System.out.println(line);
}
//获取进程的pid号
if(storeLine!=""){
int beginIndex = storeLine.indexOf("exe");
int endIndex = storeLine.indexOf("Console");
String pid = storeLine.substring(beginIndex+3, endIndex).trim();
System.out.println("this process id is "+pid);
}else{
System.out.println("this process is not exist");
} 
 

 

 

分享到:
评论
1 楼 hazmy 2009-09-15  
如果是cmd.exe呢?而且有多个,你怎么判断哪个是你想要的??

相关推荐

Global site tag (gtag.js) - Google Analytics