1. 程式人生 > >java執行cmd命令工具實現

java執行cmd命令工具實現

        在某些情況下,java也會呼叫cmd執行某些命令。例如重啟啊什麼的,之前寫了一個執行cmd命令的一個工具類,大家可以參考一下,根據自身情況進行調整。

        執行String字串類的命令

public String runCommands(String cmds){

		String str = "";
		String errStr = "";
		String charset = Charset.defaultCharset().toString();
		try {
			Process p = Runtime.getRuntime().exec(cmds);
			InputStream err = p.getErrorStream();
			InputStream in = p.getInputStream();
			str = processStdout(in, charset);
			errStr = processStdout(err, charset);
			if(!StringUtils.isEmpty(errStr)){
				return str+errStr;
			}
		} catch (IOException e) {
			errStr = e.getMessage();
			return errStr;
		}
		return str;

	}
        執行String[]類的命令
public String runCommands(String[] cmd){

		String str = "";
		String errStr = "";
		String charset = Charset.defaultCharset().toString();
		try {
			Process p = Runtime.getRuntime().exec(cmd);
			InputStream err = p.getErrorStream();
			InputStream in = p.getInputStream();
			str = processStdout(in, charset);
			errStr = processStdout(err, charset);
			if(!StringUtils.isEmpty(errStr)){
				return str+errStr;
			}
		} catch (IOException e) {
			errStr = e.getMessage();
			return errStr;
		}
		return str;

	}
        解析返回資訊
public String processStdout(InputStream in, String charset) throws IOException {
		String s = "";
		String str = "";
		InputStreamReader insr = new InputStreamReader(in);
		BufferedReader buffer = new BufferedReader(insr);
		try {
			while ((s=buffer.readLine())!= null){
				if(StringUtil.isEmpty(str)){
					str = str+s;
				}else{
					str = "\n"+str+s;
				}
			}
		} catch (IOException e) {
			throw e;
		} finally {
			buffer.close();
			insr.close();
		}

		return str;
	}