2012-09-10 33 views
1

我正在編寫一個基本上通過java發送linux命令並打印回輸出的程序。它工作正常,如果輸出只有一行,但對於多行輸出我無法弄清楚我做錯了什麼。例如,要檢查我用的是「免費的」命令的內存使用情況,但它只返回線1和3。這裏是我的代碼:打印由BufferedReader返回的多行

if (clinetChoice.equals("3")) 
    { 
     String command = "free"; 

     Process process = Runtime.getRuntime().exec(command); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); 

     System.out.println("You Chose Option Three"); 

     String line;    

     while ((line = reader.readLine()) != null) 
     { 
      output += line; 
      System.out.println(line); 
      line = reader.readLine(); 
     } 

    } 

當我運行這個它只返回:

total used free share buffers cached 
-/+ buffers/cache: 6546546 65464645 

客戶端代碼:

while ((fromServer = input.readLine()) != null) 
    { 
     System.out.println("Server: " + fromServer);    
     if (fromServer.equals("Bye")) 
      break;   

     System.out.print("Enter your choice: "); 
     fromClient = stdIn.readLine().trim(); 

     if(fromClient.equals("1")) 
     { 
      System.out.println("Client: " + fromClient); 
      output.println(fromClient); 

     } 
     if(fromClient.equals("2")) 
     { 
      System.out.println("Client: " + fromClient); 
      output.println(fromClient); 

     } 
     if(fromClient.equals("3")) 
     { 
      System.out.println("Client: " + fromClient); 
      output.println(fromClient); 

     } 
     if(fromClient.equals("4")) 
     { 
      System.out.println("Client: " + fromClient); 
      output.println(fromClient); 
      break; 

     } 


    } 

回答

6

你在兩個你的循環測試的循環體調用readLine。因此,對於循環的每次迭代,readLine被調用兩次,其中一個結果被丟棄:它不打印或添加到output。這與您描述的結果相符。

這個循環應該足夠了:

while ((line = reader.readLine()) != null) 
{ 
    output += line + System.getProperty("line.separator"); 
    System.out.println(line); 
} 

如果你只是想一次打印整個輸出,因爲你是在爲你output變量收集輸出,可以移動println出來的循環:

while ((line = reader.readLine()) != null) 
{ 
    output += line + System.getProperty("line.separator"); 
} 

System.out.println(output); 
+0

這個答案是正確的,只是在'loop = reader.readLine();'在你的循環底部。 – lynks

+0

這工作,謝謝。唯一的事情是它將同一行上的所有內容都返回。我添加了輸出+ =行+「\ n」;但是一次只打印一行,而不是一次打印所有內容。 – Nick

+0

@Nick:'readLine'消耗換行符,因此您需要將其添加回去。如果你想一次打印所有的輸出,在你的循環中刪除'println'並在循環之後執行'println(output)'。我將添加到這個答案 – pb2q

1

只需使用這個......你所呼叫的readLine()兩次....

while ((line = reader.readLine()) != null) 
     { 

      System.out.println(line); 

     } 

如果要指定數據輸出varible..then做到這一點,而循環中..

output = output + line;

1

我要指出的是除了的意見重新。使用readline()兩次,您應該同時嚴格使用stdout/stderr。否則,由於您沒有使用它,因此存在阻止流程輸出的風險。有關更多信息,請參閱this SO answer