fbpx
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


I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Advertisements
%d bloggers like this: