網上大多數博客的內容都是使用Runtime.getRuntime().exec來執行shell語句,但是這種方法在執行javac或者java -version的時候返回結果為空
Runtime.getRuntime().exec("cmd /c "+cmd);
找了許久終於發現一篇博客中的方法,使用ProcessBuilder類可以解決這個問題
public class ShellUtil {
public String run(String cmd) { Runtime runtime = Runtime.getRuntime(); StringBuffer b=new StringBuffer(); BufferedReader br = null; String sys = System.getProperties().getProperty("os.name").toUpperCase(); try { cmd = cmd.trim();
//獲取當前項目的路徑 String path = this.getClass().getResource("/").getPath(); int i = path.indexOf("crds-platform"); path = path.substring(1,i); path = path.replace("/","\\\\"); path = path + "Report"+"\\\\data.txt"; File file = new File(path); if(!file.exists()) { file.createNewFile(); } ProcessBuilder pb = new ProcessBuilder(); if(sys.indexOf("WINDOWS") != -1) { pb = new ProcessBuilder().command("cmd.exe", "/c", cmd).inheritIO(); } else { pb = new ProcessBuilder().command("/bin/sh", "-c", cmd).inheritIO(); } pb.redirectErrorStream(true);
//將執行結果寫入file中 pb.redirectOutput(file); //Process process = pb.start(); pb.start().waitFor();
//從file中讀出執行結果 InputStream in = new FileInputStream(file);
//轉碼,防止中文亂碼 br= new BufferedReader(new InputStreamReader(in,Charset.forName("GBK"))); String line=null; while ((line=br.readLine())!=null) { b.append(line+"\n"); //System.out.println(line); } file.delete(); /* Process p = Runtime.getRuntime().exec("cmd /c "+cmd); br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.forName("GBK"))); String line=null; while ((line=br.readLine())!=null) { b.append(line+"\n"); }*/ } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } return b.toString(); } }