標籤: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?
- #!/bin/sh
- echo Begin word cluster
- /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
- echo The word classes were saved to file classes.csv
然後是JAVA調用代碼
[java] view plain copy print?
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
-
- public class RunShell {
- public static void main(String[] args){
- try {
- String shpath="/home/felven/word2vec/demo-classes.sh";
- Process ps = Runtime.getRuntime().exec(shpath);
- ps.waitFor();
-
- BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
- StringBuffer sb = new StringBuffer();
- String line;
- while ((line = br.readLine()) != null) {
- sb.append(line).append("\n");
- }
- String result = sb.toString();
- System.out.println(result);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
其實就是一個Process類進行調用,然後把shell的執行結果輸出到控制台下。
需要注意的是,在調用時需要執行waitFor()函數,因為shell進程是JAVA進程的子進程,JAVA作為父進程需要等待子進程執行完畢。
另外在eclipse控制台輸出時並不是邊執行邊輸出,而是shell全部執行完畢後輸出,所以如果執行較為複雜的shell指令碼看到沒有輸出時可能會誤以為沒有執行,這個時候看看終端裡面的進程,TOP命令一下就能看到其實shell指令碼已經開始執行了。
JAVA調用Shell指令碼