How to execute a shell command in Java

    public String executeCommand(String command) {
	StringBuffer out = new StringBuffer();

	Process p;
	try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line = "";
            while ((line = reader.readLine())!= null) {
		out.append(line + "\n");
            }

	} catch (Exception e) {
            e.printStackTrace();
	}

	return out.toString();
    }

Leave a Reply