2012-09-10 34 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