2016-07-14 82 views
0

我想執行這個命令:的Java執行「時間捲曲-s」命令

time curl -s 'URL HERE' 

在Java和得到的結果,如:

real 0m0.293s 
user 0m0.100s 
sys  0m0.052s 

什麼將是最好的方式做這個?

+0

編寫代碼?我們不是爲你這樣做的。你編寫代碼,我們(可能)嘗試幫助修復它。 –

+0

我去回答這個問題,發現它實際上非常困難。 –

回答

2

你執行的一般方法的指令將調用Runtime.getRuntime().exec()Runtime.getRuntime().exec()將執行您提供的命令。然而,有幾個注意事項:

首先,time是一個shell內置命令。如果你只需要調用

Runtime.getRuntime().exec("time curl -s 'http://www.google.com/'"); 

,那麼你會得到以下錯誤:

Exception in thread "main" java.io.IOException: Cannot run program "time": error=2, No such file or directory 

看起來你可以用sh -c解決這個問題:

Runtime.getRuntime().exec("sh -c \"time curl -s 'http://www.google.com/'\""); 

但你不能。 exec()使用空格字符將參數拆分爲字符串而不考慮引號!這很煩人。您可以修復與ProcessBuilder

Process process = new ProcessBuilder("sh", "-c", "time curl -s 'http://www.google.com/'").start(); 

此命令將不會失敗,但也不會出現做任何事情!這是因爲Java不會自動將執行的命令的輸出發送到標準輸出。如果你想這樣做,你必須手動複製輸出:

Process process = new ProcessBuilder("sh", "-c", "time curl -s 'http://www.google.com/'").start(); 
InputStream in = process.getInputStream(); 
int i; 
while (-1 != (i = in.read())){ 
    System.out.write(i); 
} 

這複製輸出,但不是錯誤。您可以使用process.getErrorStream()(它返回InputStream)執行相同的複製程序。你也可以使用redirectErrorStream()

Process process = new ProcessBuilder("sh", "-c", "time curl -s 'http://www.google.com/'").redirectErrorStream(true).start(); 
InputStream in = process.getInputStream(); 
int i; 
while (-1 != (i = in.read())){ 
    System.out.write(i); 
} 

THAT是如何正確地在Java中執行命令。

編輯:You could also download the file in Java natively.在這種情況下,您可以使用System.nanoTime()來計算需要多長時間。