Execute shell command from Java

Sometime we need to execute shell commands from java code. Like in case where we use jar file in our java code and running that jar from shell command like java -jar <jar_name.jar> or in order to find java version from shell command like java -verison

In this tutorial I am going to write a sample program wich execute the same command from java code.


CmdTest.java

import java.io.*;

public class CmdTest
{
 

public static void main(String[] args) throws Exception
{
String arg1 = "cmd.exe";
String commandToExec = "java -version";

final String folder= System.getProperty("user.dir")+"/lib\"";
String[] command = { arg1, "/C", "cd \""+folder+"&&"+commandToExec};

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while (true)
{
line = r.readLine();
if (line == null)
{
break;
}

System.out.println(line);
}
}
}

Output:


java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)



8 features of java 8

JAVA 8 or JDK 1.8 is a major release of JAVA language. Its initial version was released on 18 March 2014. With the Java 8 release, Java provided support for functional programming, new JavaScript engine, new APIs for date time manipulation, new streaming API and many more.


8 New Features of Java 8



The most significant features of java 8 are below:

Lambda expression: 

It adds functional processing capability to Java. A new language feature, has been introduced in this release. They enable you to treat functionality as a method argument, or code as data. Lambda expressions let you express instances of single-method interfaces (referred to as functional interfaces) more compactly.

Method references: 

Referencing functions by their names instead of invoking them directly. Using functions as parameter. Provide easy-to-read lambda expressions

Default method: 

Default methods enable new functionality to be added to the interfaces of libraries and ensure binary compatibility with code written for older versions of those interfaces.


Stream API: 

New Stream API (java.util.stream ) to support functional-style operations on streams of elements. The Stream API is integrated into the Collections API, which enables bulk operations on collections, such as sequential or parallel map-reduce transformations.

Date Time API: 

The Date/Time API is moved to java.time package and Joda time format is followed. Another good news is that, most classes are Thread safe and immutable.

Nashorn, JavaScript Engine: 

A Java-based engine to execute JavaScript code. It is similar to the V8 engine provided by chrome over which Node.js runs. It is compatible with Node.js applications while also allowing actual Java libraries to be called by the javascript code running on server. This is exciting to say at the least as it marries scalability and asynchronous nature of Node.js with safe and widespread server side Java middleware directly.


New tools:

New compiler tools and utilities are added like ‘jdeps’ to figure out dependencies.

Optional Values:

Emphasis on best practices to handle null values properly. Java SE 8 introduces a new class called java.util.Optional that can alleviate some of these problems.

References: 
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

Java 8 - Lambda Expressions

Lambda expressions are introduced in Java 8 and are assumed to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and it simplifies the development very much.
A lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (->) and a function body.

Syntax

A lambda expression is characterized by the following syntax:

parameter -> expression body

Following are the important characteristics of a lambda expression

Optional type declaration: No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.

Optional parenthesis around parameter:  No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
Optional curly braces: No need to use curly braces in expression body if the body contains a single statement.
Optional return keyword: The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.



Lambda Expressions Example


Create the following Java program using eclipse editor

LambdaExpressionTest.java

public class LambdaExpressionTest {
public static void main(String args[]) {
LambdaExpressionTest test = new LambdaExpressionTest();

// with type declaration
MathOperation addition = (int a, int b) -> a + b;

// with out type declaration
MathOperation subtraction = (a, b) -> a - b;

// with return statement along with curly braces
MathOperation multiplication = (int a, int b) -> {
return a * b;
};

// without return statement and without curly braces
MathOperation division = (int a, int b) -> a / b;

System.out.println("10 + 5 = " + test.operate(10, 5, addition));
System.out.println("10 - 5 = " + test.operate(10, 5, subtraction));
System.out.println("10 x 5 = " + test.operate(10, 5, multiplication));
System.out.println("10 / 5 = " + test.operate(10, 5, division));

// without parenthesis
GreetingService greetService1 = message -> System.out.println("Hi " + message);

// with parenthesis
GreetingService greetService2 = (message) -> System.out.println("Hi " + message);

greetService1.sayMessage("Guest");
greetService2.sayMessage("User");
}

interface MathOperation {
int operation(int a, int b);
}

interface GreetingService {
void sayMessage(String message);
}

private int operate(int a, int b, MathOperation mathOperation) {
return mathOperation.operation(a, b);
}
}

When you execute the program its output look like:

10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hi Guest
Hi Welcome to my blog

Important points to be considered from above example.


Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.

Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.