Run System Command from Java Program - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

demo-image

Run System Command from Java Program

Share This

In this tutorial, we will discuss how to run a system command from a Java program.

If you want to check list of processes on your system and you are an Unix user, you will definitely use ps -ef command. In the following program, we will run the command from Java program.

1
2
3
4
5
6
7
8
9
10
package com.t4b.test;
import java.io.*;
public class JavaRunCommand {
public static void main(String args[]) {
String s = null;
try {
Process p = Runtime.getRuntime().exec("ps -ef");
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Retrieve System Information

To retrieve system information you may try the following code.


1
2
3
4
5
6
7
8
9
10
package com.t4b.test;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Map;
import java.util.Set;
public class SystemInfo {
public static void main(String[] args) {
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Check IP Address

If you want to check IP address of your local machine try the following code.


1
2
3
4
5
6
7
8
9
10
package com.t4b.test;
import java.net.InetAddress;
class IPAddress
{
public static void main(String args[]) throws Exception
{
System.out.println(InetAddress.getLocalHost());
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Open Notepad

If you want to open an applicatication using Java program, you may try the following.


1
2
3
4
5
6
7
8
9
10
package com.t4b.test;
import java.util.*;
import java.io.*;
class Notepad {
public static void main(String[] args) {
Runtime rs = Runtime.getRuntime();
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Now, you may think that why are we going to write a complex code, where we can directly run those commands on terminal?

Here, the answer is: sometimes a program needs to be executed by some other program whithout human intervension. Thus this technique is used to automate the system.


1
2
3
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


Happy Exploring!

Comment Using!!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.