2017-01-02 201 views
-6

如何使用輸入參數(如「./flows.sh suspend」)執行shell腳本文件並將結果打印到在linux中使用java的文件?如何使用java執行shell腳本

+1

_「如果可能,請回復完整的代碼」_ - 保證吸引downvotes並關閉您的問題。 StackOverflow不是一個「給我teh codez」網站,並且在沒有顯示任何努力的情況下詢問代碼被認爲是粗魯和偏離主題。 –

回答

1

這是一個簡單的代碼來執行shell腳本並讀取其輸出:

import java.io.*;                

public class Test {               
    public static void main(String[] args) throws Exception {     
    String[] command = { "./flows.sh", "suspend" };   
    Process process = Runtime.getRuntime().exec(command);      
    BufferedReader reader = new BufferedReader(new InputStreamReader( 
     process.getInputStream()));           
    String s;                 
    while ((s = reader.readLine()) != null) {         
     System.out.println("Script output: " + s); // Replace this line with the code to print the result to file      
    }                   
    }                   
}  

要打印到文件時,只需更換的System.out.println的代碼寫入到文件

+0

它......比這更復雜。僅僅對於初學者來說,'。/'是指什麼,shell在哪裏介入? –

+1

@JimGarrison'。/'指向當前目錄,並且需要抑制PATH查找。解釋腳本的shell由內核根據腳本的shebang生成。沒有比這更多的東西了,使用ProcessBuilder可以更輕鬆地將重定向直接設置到文件中。 –

+0

@JimGarrison這是另一個問題......我只是把一個工作解決方案,如何從Java執行一個shell腳本並獲得它的輸出,因爲我認爲它是主要問題 – xBlackout