×

Welcome to TagMyCode

Please login or create account to add a snippet.
1
0
 
1
Language: Java
Posted by: Solr Trovaprezzi
Added: May 18, 2015 2:52 PM
Views: 30
  1. import org.apache.commons.lang3.StringUtils;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7.  
  8. public class Bash {
  9.     public static String runScript(String command) throws IOException, InterruptedException {
  10.         Process p = Runtime.getRuntime().exec(new String[]{"sh", "-c", command});
  11.         return executeProcess(p);
  12.     }
  13.  
  14.     private static String executeProcess(Process p) throws InterruptedException, IOException {
  15.         p.waitFor();
  16.         ArrayList<String> output = new ArrayList<>();
  17.         String line;
  18.  
  19.         try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
  20.             while ((line = br.readLine()) != null) {
  21.                 output.add(line);
  22.             }
  23.         }
  24.         return  StringUtils.join(output, "\n");
  25.     }
  26. }
  27.