Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

to run shell script through java

I want to run a shell script through java .I am using license generation tool,It can be call with the help of ./LicenseGen.sh command,under it I require to execute another command create licensekey -x license-input.xml which create a new licensekey.xml file where license-input.xml is a input file and licensekey is a output xml file how it is posssible in java please help me.

my code is

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);
       }

     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't execute the script directly since it has to be interpreted by a shell like bash. Note that bash is an executeable.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...