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)



No comments:

Post a Comment