2013-07-23 222 views
2

我知道我們可以在java程序中運行linux終端命令,如下面的代碼顯示主目錄的「ls」命令。從java程序運行linux命令txl

String[] cmd1 = { 
     "/bin/sh", 
     "-c", 
     "cd ../.. && ls"}; 
     Process child1 = Runtime.getRuntime().exec(cmd1); 
     child1.waitFor(); 

final BufferedReader is = new BufferedReader(new InputStreamReader(child1.getInputStream())); 
     String line; 
     while ((line = is.readLine()) != null) { 

      System.out.println("output is: "+line); 
     } 

但我不知道「/ bin/sh」和「-c」是什麼意思?我在網上搜索它,有人使用「bash」或其他。如果我只運行命令「cd ../ .. & & ls」,我會得到相同的結果。

所以,如果在終端爲「通心絡-o輸出INPUTFILE」,其中「通心絡」已安裝的工具命令,如何寫在java嗎?我試過

String[] cmd1 = { 
     "/bin/sh", 
     "-c", 
     "cd ../.. && txl -o output inputFile"}; 

但是無法得到結果。我添加「cd ../ ..」首先從工作空間進入主目錄,因爲txl安裝在主目錄bin目錄中。

任何人都可以給我一些建議嗎?

編輯:

我這種格式的作品犯了一個愚蠢的拼寫錯誤,命令!

+0

我個人會避免直接使用'Runtime.exec',而是使用'ProcessBuilder'。話雖如此,你應該拆分你的cmd數組,以便每個元素代表一個單獨的參數,這個參數將被髮送到你正在執行的命令中。你的例子會提示'cd ../ .. && ls'會作爲你正在執行的命令的單個參數出現,這不是你想要的 – MadProgrammer

+0

謝謝,madprogrammer。如果是這樣,寫入cmd1'String [] cmd1 = {「/ bin/sh」, 「-c」,「cd ../ ..」,「txl -o output inputFile」}或' String [] cmd1 = {「cd ../ ..」,「txl -o output inputFile」}'?或者你能告訴我如何編寫cmd1?謝謝! @MadProgrammer – Eve

+0

我會建議更類似'{「/ bin/sh」,「-c」,「cd」,「../ ..」,「&&」,「txl」,「-o」,「output 「,」inputFile「}'但你可能需要試驗它 – MadProgrammer

回答

0

/bin/sh是一個程序,這是shell,選項-c指定以下是由shell執行的命令(這是您的cmd1的第三個「行」:cd ../.. && ls

編輯:

在這種情況下是對所必要的執行殼,只執行cd ../.. && ls是行不通的,因爲像cdls之間的&&運營商都沒有Java,但通過外殼的理解。

+0

謝謝,摩根。如果是這樣,它應該適用於命令「cd ../ .. && txl -o output inputFile」吧?或者java程序只能運行一些默認命令,如ls,cd,dir等? @morgano – Eve

+0

@Eve我修復了我的答案,實際上,如果您嘗試僅執行cd ../ .. && ls,您將得不到相同的結果 – morgano

0

你可以找到here什麼LS每個參數做:

-c 
with -lt: sort by, and show, ctime (time of last modification of file status information) with -l: show ctime and sort by name otherwise: sort by ctime 

爲了在Java執行程序並等待它完成,你可以使用this