Wednesday, October 19, 2016

Execute Shell Script from JAVA

Deploy this java program to a unix box where java is installed

The below code would run the command you specify



import java.io.*;

public class ExportToExcel {
    public ExportToExcel() {
        super();
    }

  
    public static void main(String args[]) {
      
        ExportToExcel e = new ExportToExcel();
      
       //in UNIX

       String command = "pwd";

        String output = e.executeCommand(command);

        System.out.println(output);

     
    }


    public String executeCommand(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            p.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return output.toString();

    }

}


Output:


  • /home/usr/javaprogram/

Reference;
http://stackoverflow.com/questions/21598359/compiling-java-file-from-another-java-class
https://www.mkyong.com/java/how-to-execute-shell-command-from-java/

1 comment:

  1. Small storage basket with lid are essential for organizing and tidying up any space. Crafted from durable materials like wicker, bamboo, or fabric, these baskets offer a stylish solution for storing items such as toys, toiletries, or office supplies. The lid helps keep contents secure and dust-free, ensuring a neat appearance. Their compact size fits conveniently on shelves, in closets, or on countertops, adding a touch of rustic charm or modern elegance to your decor. Small storage baskets with lids are versatile and durable, making them an ideal choice for maintaining a tidy and organized home environment.

    ReplyDelete