Using the command line with java
Posted in Development, Java, Linux, Resourcen on September 20th, 2010 by admin – Be the first to commentIf you are looking for a simple way to use the command line via Java use this wrapper class. It offers a simple solution for a simple task. KISS!
How to use it:
System.out.println(new CommandLine("/var").exec("ls"));
And here is the class:
import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; public class CommandLine { private String path ; public CommandLine() { path = "/"; } public CommandLine(String path) { this.path = path; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String exec(String cmd) { String s = null; String ret = ""; File workDir = new File(path); try { Process p = Runtime.getRuntime().exec(cmd, null, workDir); int i = p.waitFor(); if (i == 0){ BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((s = stdInput.readLine()) != null) { ret = ret + s + "\n"; } } else { BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((s = stdErr.readLine()) != null) { ret = ret + s + "\n"; } } } catch (Exception e) { e.printStackTrace(); } return ret; } }
