Executer des commandes système
Submitted by PiTiLeZarD on Thu, 04/05/2007 - 14:40
Tagged:
Vulgairement j'ai fait un wrapper au Runtime.getRuntime.exec("commande"); et je vous le file puisque je trouve ça assez pratique (et que ça m'évitera d'alourdir le prochain billet qui vient juste après !)
On s'en sert comme ceci :
//n'essayez pas cette commande :) ProcessHelper.exec("rm -Rf /*"); //si on veut que la sortie d'erreur génère une exception !: ProcessHelper.exec(maCommande, true) //Si on veut récupérer la sortie ! String[] results = ProcessHelper.exec("ls -al");
Et voici la classe qui va bien :
public class ProcessHelper { public static String[] exec(String cmd) { try { return exec(cmd, false); } catch (HelperException e) { log.error(e,e); } return new String[0]; } public static String[] exec(String cmd, boolean throwExceptions) throws HelperException { try { log.trace("$ " + cmd); Process proc = Runtime.getRuntime().exec(cmd); proc.waitFor(); String line = null; /*- error -*/ BufferedReader error = new BufferedReader(new InputStreamReader(proc.getErrorStream())); StringBuffer errorString = new StringBuffer(""); while ((line = error.readLine()) != null) { log.warn("> " + line); errorString.append(line); errorString.append("\n"); } if (throwExceptions && (errorString.length() > 0)) { throw new HelperException(errorString.toString()); } /*- standard input -*/ BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream())); Collection inputStrings = new ArrayList(); while ((line = input.readLine()) != null) { log.debug("> " + line); inputStrings.add(line); } return (String[])inputStrings.toArray(new String[inputStrings.size()]); } catch (Exception e) { throw new HelperException(e); } } }
