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

Posted 『天堂有路』

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 执行CMD命令打开和杀死一个程序相关的知识,希望对你有一定的参考价值。

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命令打开和杀死一个程序的主要内容,如果未能解决你的问题,请参考以下文章

java如何执行cmd命令

怎么在cmd里面运行 java

如何在活动的 onSaveInstanceState() 之后杀死所有打开的片段

macOS-代码调用Terminal执行脚本或者杀死进程窗口

如何用CMD命令结束一个进程和打开一个程序?

如何使用Java执行cmd命令