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


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



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



Java代码

 
    
  
1. ProcessBuilder pb = new ProcessBuilder("tasklist");   
2. try
3. Process p = pb.start();   
4. new BufferedReader(new
5. String line;   
6. "";    
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. 3, endIndex).trim();    
17. "this process id is "+pid);    
18. else{    
19. "this process is not exist");    
20. }