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");
}
本文介绍如何使用Java调用BAT批处理文件,并演示了如何监控Windows下特定进程的状态,包括启动和运行情况。
1040

被折叠的 条评论
为什么被折叠?



