Pages Navigation Menu

Coding is much easier than you think

Executing Shell command from Java code

Shell script in java
 
In this post let us learn the way of executing a shell command through a java class.

In JAVA we have a class called “java.lang.Runtime” which is used to interact with Runtime system and has facility to execute any shell commands using Runtime.getRuntime().exec() method.

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class ExecuteProcess {
	public void executeCommand() {
		String command = "ls -ltr";
		Runtime run = Runtime.getRuntime();
		Process process = null;
		try {
			process = run.exec(command);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		try {
			process.waitFor();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

               BufferedReader br = new BufferedReader(new InputStreamReader(
				process.getInputStream()));
		String line = "";
		try {
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

Note: This kind of implementations are discourage by java programming language since you will lose platform independence which is why we mostly used JAVA.

 
 Reference

 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.