java基礎/java調用shell命令和腳本


一。項目需求:

從某一機構獲取證書,證書機構提供小工具,執行.sh腳本即可啟動服務,本地調用該服務即可獲取證書。

問題:linux服務器啟動該服務,不能關閉。一旦關閉,服務即停止。

解決方案:java調用shell命令,利用spring容器啟動即執行方案。

參考博文:http://zohan.iteye.com/blog/1709136

項目結構:

原碼:

1。RuntimeUtils.java

 1 package com.csvalue.common;
 2 
 3 import org.springframework.util.StringUtils;
 4 
 5 import java.io.File;
 6 import java.io.IOException;
 7 
 8 /*
 9 * java調用sheet腳本工具類
10 * */
11 public class RuntimeUtils {
12     public static Process exec(String command, String envp, String dir)
13             throws IOException {
14         String regex = "\\s+";
15         String args[] = null;
16         String envps[] = null;
17         if (!StringUtils.isEmpty(command)) {
18             args = command.split(regex);
19         }
20         if (!StringUtils.isEmpty(envp)) {
21             envps = envp.split(regex);
22         }
23         return Runtime.getRuntime().exec(args, envps, new File(dir));
24     }
25 }
View Code

2。p10Server.java

 1 package com.csvalue.service.impl;
 2 
 3 import com.csvalue.common.RuntimeUtils;
 4 import org.slf4j.LoggerFactory;
 5 import org.springframework.stereotype.Component;
 6 import org.springframework.stereotype.Service;
 7 
 8 import javax.annotation.PostConstruct;
 9 
10 /*
11 * Spring容器啟動即啟動sh腳本文件
12 * */
13 @Service
14 public class P10Server {
15     final org.slf4j.Logger log = LoggerFactory.getLogger(getClass());
16     @PostConstruct
17     public void init(){
18         System.out.println("啟動p10服務:init....");
19         String command = "sh startup.sh";
20         String dir=RuntimeUtils.class.getResource("/").getPath()+"KTServer";
21         System.out.println(dir);
22         try {
23             RuntimeUtils.exec(command, null, dir);
24             //Process process = RuntimeUtils.exec(command, null, dir);
25             //int i = process.waitFor();
26            // System.exit(i);
27         }catch (Exception e){
28             log.error("啟動p10異常:"+e.getMessage());
29         }
30 
31     }
32 }
View Code

注意:p10Server.java中注釋掉的部分。若開啟,則服務一直啟動不起來!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM