JAVA調用Shell指令碼

來源:互聯網
上載者:User

標籤:idt   cbo   padding   out   log   .exe   trace   keyword   top命令   

在實際項目中,Java有時候需要調用C寫出來的東西,除了JNI以外,我認為一種比較好的方法是JAVA調用Shell。先把C寫出來的make成可執行檔,然後再寫一個shell指令碼執行該可執行檔,最後是JAVA調用該shell指令碼。

JAVA調用很簡單,例子如下:

首先是shell指令碼

 

[plain] view plain copy print?
  1. #!/bin/sh  
  2. echo Begin word cluster  
  3. /home/felven/word2vec/word2vec -train /home/felven/word2vec/resultbig.txt -output /home/felven/word2vec/classes.csv -cbow 0 -size 200 -window 5 -negative 0 -hs 1 -sample 1e-3 -threads 12 -classes 2000  
  4. echo The word classes were saved to file classes.csv  


然後是JAVA調用代碼

 

 

[java] view plain copy print?
  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3.   
  4. public class RunShell {  
  5.     public static void main(String[] args){  
  6.         try {  
  7.             String shpath="/home/felven/word2vec/demo-classes.sh";  
  8.             Process ps = Runtime.getRuntime().exec(shpath);  
  9.             ps.waitFor();  
  10.   
  11.             BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));  
  12.             StringBuffer sb = new StringBuffer();  
  13.             String line;  
  14.             while ((line = br.readLine()) != null) {  
  15.                 sb.append(line).append("\n");  
  16.             }  
  17.             String result = sb.toString();  
  18.             System.out.println(result);  
  19.             }   
  20.         catch (Exception e) {  
  21.             e.printStackTrace();  
  22.             }  
  23.     }  
  24. }  


其實就是一個Process類進行調用,然後把shell的執行結果輸出到控制台下。

 

需要注意的是,在調用時需要執行waitFor()函數,因為shell進程是JAVA進程的子進程,JAVA作為父進程需要等待子進程執行完畢。

另外在eclipse控制台輸出時並不是邊執行邊輸出,而是shell全部執行完畢後輸出,所以如果執行較為複雜的shell指令碼看到沒有輸出時可能會誤以為沒有執行,這個時候看看終端裡面的進程,TOP命令一下就能看到其實shell指令碼已經開始執行了。

JAVA調用Shell指令碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.