Executing Programs in Java

The program arguments will be executed through this ‘shell’. You can make a loop that will make the following snippet a real shell.

import java.io.*;

public class SimpleShell {
	public static void main(String[] argv) {
	String line;
	StringBuilder output = new StringBuilder();

	try {
		Process p = Runtime.getRuntime().exec(argv);
		BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
		while ((line = input.readLine()) != null) {
			output.append(line).append("\n");
		}

		System.out.println(output);
	} catch (Exception e) {
		e.printStackTrace();
	}

	}
}

Leave a Reply

Your email address will not be published.