码迷,mamicode.com
首页 > 编程语言 > 详细

Java 执行CMD命令打开和杀死一个程序

时间:2017-11-27 15:19:32      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:for   ogg   public   ram   tde   error   nal   led   input   

public class CmdExec{
	private boolean programFlag = false;
	private static final Logger logger = Logger.getLogger(CmdExec.class);
    private static CmdExec cmdExec =null;
    public static CmdExec getCmdExec(){
    	if(cmdExec==null){
    		cmdExec = new CmdExec();
    	}
    	return cmdExec;
    }
    
    /** 
     * @Title: cmdExec
     * @Description: 执行cmd命令
     * @param @param cmdStr
     * @return void
     * @throws 
     */
    public void cmdExec(String cmd,String programName){
    	Desktop desktop = Desktop.getDesktop();
    	Runtime rt = Runtime.getRuntime();
        Process proc = null;
        String cmdStr = "tasklist /nh /fo csv";
        try {
            proc = rt.exec(cmdStr);
            String line="";
        	InputStreamReader isr = new InputStreamReader(proc.getInputStream());  
        	BufferedReader br = new BufferedReader(isr);  
        	while ((line = br.readLine()) != null) {
	    		if(line.indexOf(programName)>-1){
	    			programFlag = true;
	    		}
	    	}
        	if(!programFlag){
        		desktop.open(new File(cmd));
        	}
        	br.close();
        	isr.close();
        	proc.waitFor();
        	proc.destroy();
        } catch (Exception e1) {
            logger.error(cmdStr+" exec failed! " +e1.getMessage());
        }
    }
    
    /** 
     * @Title: cmdKill
     * @Description: 杀死指定的程序,程序全名称如notepad.exe
     * @param @param programName
     * @param @throws IOException
     * @return void
     * @throws 
     */
    public void cmdKill(String programName){
        Runtime rt = Runtime.getRuntime();
        Process proc = null;
        String cmdStr = "tasklist /nh /fo csv";
        try {
            proc = rt.exec(cmdStr);
            String line="";
        	InputStreamReader isr = new InputStreamReader(proc.getInputStream());  
        	BufferedReader br = new BufferedReader(isr);
        	while ((line = br.readLine()) != null) {
	    		if(line.indexOf(programName)>-1){
	    			Runtime.getRuntime().exec("taskkill /f /t /im "+programName+"");
	    		}
	    	}
	    	 proc.waitFor();
	         proc.destroy();
        } catch (Exception e1) {
            logger.error(cmdStr+" exec failed! "+e1.getMessage());
        }
    }
}

  

Java 执行CMD命令打开和杀死一个程序

标签:for   ogg   public   ram   tde   error   nal   led   input   

原文地址:http://www.cnblogs.com/rvs-2016/p/7903890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!