Run shell script through java

I want to run a shell script through java. I use the tool to create a license. It can be called using the command. /LicenseGen.sh. I need to run another command to create a license -x license-input.xml which creates a new licensekey.xml file, where license-input.xml is the input file and licensekey is the XML output file, as possible in java, please help me .

my code

import java.io.*;
import java.util.*;

public class ProcessExample {

/**
 * @param args
 */
 public static void main(String args[]) throws IOException {

       File file=new File("/opt");
      // List<String> list=new List<String>();
       ProcessBuilder processBuilder = new ProcessBuilder("./LicenseGen.sh");
       processBuilder.directory(file);

        Process process=processBuilder.start();      
       //processBuilder.command("create licensekey -x license-input.xml");
       //process=processBuilder.start();
       InputStream is = process.getInputStream();
       InputStreamReader isr = new InputStreamReader(is);
       BufferedReader br = new BufferedReader(isr);

       String line;

       System.out.printf("Output of running %s is:", 
          Arrays.toString(args));

       while ((line = br.readLine()) != null) {
         System.out.println(line);
       }

     }
}
+3
source share
3 answers

You cannot execute the script directly, as it must be interpreted by a shell like bash. Note that bash is doable.

ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/path/LicenseGen.sh");  
+6
source

Using commons cli http://commons.apache.org/cli/ Good luck!

0

I used JSchextensively for remote login and script execution. I used google Expect4jc JSchto execute scripts on remote machines in standby mode (send / wait). Since you must execute the command one by one, you can try this.

It can also be used for local execution that you require. The only worry is that you need to login (into your local machine) for execution.

For jsch go to http://www.jcraft.com/jsch/
For Expect4j go to http://code.google.com/p/expect4j/

Thank.

0
source

All Articles