java中 Process的使用

/**
 * 
 */
package com.jrs;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * @CallCmd.java
 * created at 2013-4-17 上午10:31:22 by jrs521wlh
 * 
 * @author jrs521wlh jiangrushe2010@126.com
 * @version $Revision$</br>
 * update: $Date$
 */
public class CallCmd {
 public static void main(String[] args) {
 Runtime rt = Runtime.getRuntime();
 //執行CMD命令,可以雲行本地程序
 Process p = null;
 
//		String path = "F:\\Program Files (x86)\\Tencent\\QQ\\QQProtect\\Bin\\QQProtect.exe";
// 
//		try {
//			p = rt.exec(path);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
 
 
 //調用瀏覽器,能夠打開指定的網站
//		String path="C:\\Users\\jrs521wlh\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe";
//		String chrome ="www.google.com";
//		String[] cmd={path,chrome};
//		try {
//			p = rt.getRuntime().exec(cmd);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
 printProcess();
 System.out.println("開始查找進程");
 if(findProcess("QQ.exe")){
 System.out.println("查找進程存在");
 
 }else{
 System.out.println("不存在進程");
 
 }
 
 }
 
 //打印全部的進程信息
 public static void printProcess(){
 BufferedReader buff = null;
 
 Process p = null;
 
 try {
 //打印全部進程的信息
 p = Runtime.getRuntime().exec("tasklist");
 //用流讀出來
 buff = new BufferedReader(new InputStreamReader(p.getInputStream()));
 
 System.out.println("打印進程系信息");
 
 String temp = null;
 //遍歷
 while ((temp=buff.readLine())!=null) {
 System.out.println(buff.readLine());
 
 }
 
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }finally{
 if(buff!=null){
 try {
 buff.close();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 
 }
 
 }
 /**
 * 查看進程是否運行
 * @Title: findProcess
 * @data:2013-4-17上午11:09:26
 * @author:jrs521wlh
 *
 * @return
 */
 public static boolean findProcess(String processName){
 
 BufferedReader buff = null ;
 
 try {
 //下面這句是列出含有processName的全部進程圖形名字
 Process p=Runtime.getRuntime().exec("tasklist"); 
 buff = new BufferedReader(new InputStreamReader(p.getInputStream()));
 String temp = null ;
 while((temp=buff.readLine())!=null){
 System.out.println(temp);
 if(temp.contains(processName)){
 return true;
 
 }
 
 }
 return false;
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 return false;
 }finally{
 if(buff!=null){
 try {
 buff.close();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 
 }
 
 }
}
參考:http://blog.sina.com.cn/s/blog_6f561cc301011ji4.html
相關文章
相關標籤/搜索