DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Execute Shell Command From Java

08.14.2008
| 65746 views |
  • submit to reddit
        //execute shell commands from java

String cmd = "ls -al";
		Runtime run = Runtime.getRuntime();
		Process pr = run.exec(cmd);
		pr.waitFor();
		BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
		String line = "";
		while ((line=buf.readLine())!=null) {
			System.out.println(line);
		}
    

Comments

Snippets Manager replied on Sat, 2011/03/26 - 12:41am

This example is unsafe and omits error handling, easily fixed with the following; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public void executeCommand(View view) { String cmd = "ls -al"; Runtime run = Runtime.getRuntime(); Process pr = null; try { pr = run.exec(cmd); } catch (IOException e) { e.printStackTrace(); } try { pr.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); } BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; try { while ((line=buf.readLine())!=null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }