Run System Command from Java Program - BunksAllowed

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

Community

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.

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"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("Output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } System.out.println("Standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } System.exit(0); } catch (IOException e) { System.out.println("exception"); e.printStackTrace(); System.exit(-1); } } }

Retrieve System Information

To retrieve system information you may try the following code.


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) { RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); Map<String, String> systemProperties = runtimeBean .getSystemProperties(); Set<String> keys = systemProperties.keySet(); for (String key : keys) { String value = systemProperties.get(key); System.out.printf("[%s] = %s.\n", key, value); } } }

Check IP Address

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


package com.t4b.test; import java.net.InetAddress; class IPAddress { public static void main(String args[]) throws Exception { System.out.println(InetAddress.getLocalHost()); } }

Open Notepad

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


package com.t4b.test; import java.util.*; import java.io.*; class Notepad { public static void main(String[] args) { Runtime rs = Runtime.getRuntime(); try { rs.exec("notepad"); } catch (IOException e) { System.out.println(e); } } }

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.




Happy Exploring!

No comments:

Post a Comment

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