當我應用命令命令我沒有得到任何輸出。如何在使用命令時獲得輸出或不是兩種情況?如何獲得管道命令也返回Java exec中的輸出?
public class test
{
public static void main(String args[])
{
System.out.println(
systemtest("ifconfig | awk 'BEGIN { FS = \"\n\"; RS = \"\" } { print $1 $2 }' | sed -e 's/ .*inet addr:/,/' -e 's/ .*//'"));
}
public static String systemtest(String cmds)
{
String value = "";
try
{
String cmd[] = {
"/bin/sh",
"-c",
cmds
};
Process p=Runtime.getRuntime().exec(cmd);
// Try 0: here? wrong
//p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
// Try 1: here?
//p.waitFor();
while(line!=null)
{
value += line + "\n";
line=reader.readLine();
}
// Try 2: here?
p.waitFor();
} catch(IOException e1) {
} catch(InterruptedException e2) {
}
return value;
}
p.waitFor();我在while循環或before while循環之後在最後一行中改變了這個。但結果是一樣的。我還沒有得到輸出,但是一旦我調用systemtest(「ifconfig」);它總是輸出。 – YumYumYum
編輯我嘗試的命令:ifconfig | awk'BEGIN {FS = \「\ n \」; RS = \「\」} {print $ 1 $ 2}'| sed -e's /。* inet addr:/,/'-e's /。* //' – YumYumYum
嘗試一些簡單的方法,比如'systemtest(「ifconfig | cat」)''。我有一種感覺,問題是反斜槓。正如所寫的,你在一個shell命令中看起來非法的地方有一個ASCII換行符。我現在在Windows上,所以我不能輕易檢查這個... –