In this example we will learn to run bash command and invoking a shell script file from java
Java is provided a feature to execute shell script from code
Runtime.getRuntime().exec(“”)
Above line will help us to execute bash command from java code
we need to provide the shell script inside the exec method
Printing Hostname from java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShellScriptExample {
public static void main(String[] args) {
try {
Process exec = Runtime.getRuntime().exec("hostname");
//below line will wait to execute the command
exec.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
DESKTOP-U9R6O19
Printing Ip address from Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ShellScriptExample {
public static void main(String[] args) {
try {
Process exec = Runtime.getRuntime().exec("ipconfig");
//below line will wait to execute the command
exec.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Windows IP Configuration
Ethernet adapter Ethernet:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . :
Wireless LAN adapter Wi-Fi:
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::dc21:c38b:f5cb:e4e2%17
IPv4 Address. . . . . . . . . . . : ***
Subnet Mask . . . . . . . . . . . : ****
Default Gateway . . . . . . . . . : ***
192.168.1.1
Ethernet adapter vEthernet (Default Switch):
Connection-specific DNS Suffix . :
Link-local IPv6 Address . . . . . : fe80::1859:16f5:8d15:fd81%20
IPv4 Address. . . . . . . . . . . : ***
Subnet Mask . . . . . . . . . . . : **
Default Gateway . . . . . . . . . :
Invoking Shell file from Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class InvokingShellFileExample {
public static void main(String[] args) {
try {
Process exec = Runtime.getRuntime().exec("C://script//shellscript.bat");
// below line will wait to execute the command
exec.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
F:\BeginnersBug\BegineersBug>hostname
DESKTOP-U9R6O19