Running Another Program from Java

Running Another Program from Java

You can use Java to execute another program and display its output (via a BufferedReader). Here’s the code:

import*;import java.util.ArrayList;public class ExecDemo{   static public String[] runCommand(String cmd)       throws IOException   {        // The actual procedure for process execution:      runCommand(String cmd);            // Create a list for storing  output.      ArrayList list = new ArrayList();       // Execute a command and get its process handle      Process proc = Runtime.getRuntime().exec(cmd);       // Get the handle for the processes InputStream      InputStream istr = proc.getInputStream();       // Create a BufferedReader and specify it reads       // from an input stream.      BufferedReader br = new BufferedReader(         new InputStreamReader(istr));      String str; // Temporary String variable      // Read to Temp Variable, Check for null then       // add to (ArrayList)list      while ((str = br.readLine()) != null) list.add(str);            // Wait for process to terminate and catch any Exceptions.      try { proc.waitFor(); }       catch (InterruptedException e) {        System.err.println("Process was interrupted"); }      // Note: proc.exitValue() returns the exit value.       // (Use if required)      br.close(); // Done.      // Convert the list to a string and return      return (String[])list.toArray(new String[0]);    }   // Actual execution starts here   public static void main(String args[]) throws IOException    {      try      {         // Run and get the output.         String outlist[] = runCommand(args[0]);          // Print the output to screen character by character.         // Safe and not very inefficient.         for (int i = 0; i < outlist.length; i++)            System.out.println(outlist[i]);      }      catch (IOException e) { System.err.println(e); }   }}

The comments explain the code, but briefly:

String[] runCommand(String cmd) is used to run the program:

The code creates an InputStream and "hooks" it to the executed program's output stream. A BufferedReader then reads the output and saves it to a list of strings.

After all the output has been read, waitFor is called to wait on the program to terminate. The exitValue method may be called if desired to get the program's return value.

You can use this technique to execute programs on a server and display the output. In that case, one usually would have to convert this to an applet (for use with the web) and it would be better to replace the runCommand(args[0]); line with with an arbitrary command such as runCommand("ls -a -l"); or runCommand("dir");, (depending on the OS you're running under and your specific purpose) to prevent misuse. (Imagine runCommand("rm ."))

Of course the programs you run have to be in the search path (JDK 1.2.2), but a safer approach would be to use an arbitrary path and filename, for example:


Note that the programs that are being run may not be as portable between systems as this Java application itself.

Share the Post:
XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing

data dictionary

Tools You Need to Make a Data Dictionary

Data dictionaries are crucial for organizations of all sizes that deal with large amounts of data. they are centralized repositories of all the data in organizations, including metadata such as