Java實現執行CMD命令

今日需求:使用java程序將一個tbuild腳本到數倉去執行

1.環境準備:由於工程使用docker部署,首先需要掛載一個服務器上的路徑,否則在docker容器中創建的目錄及文件在重新啓動docker服務的時候都會清掉。

2.需要在docker鏡像中打包一個tpt包

3.進入到docker容器中執行命令(tbuild -f  結果文件名)

如果tbuild命令執行沒問題,可以得到結果文件,證明環境ok

4.執行命令代碼:

cmd爲拼接好的tbuild -f 命令

public static String getRunCmdOutput(String cmd){
		  try{
			  Process p = Runtime.getRuntime().exec(cmd);
			  StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream());   
			  StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream());
			  errorGobbler.start();
			  outputGobbler.start();
			  p.waitFor(); 
			  Thread.sleep(3000);
			  System.out.println("p.exitValue():"+p.exitValue());
			  return outputGobbler.getOutput() + errorGobbler.getOutput();
		  }catch(Exception e){
			  e.printStackTrace();
			  return e.getMessage();
		  }
	  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章