2012-09-10 3 views
1

기본적으로 linux 명령을 java를 통해 보낸 다음 출력을 인쇄하는 프로그램을 작성하고 있습니다. 출력이 한 행만 인 경우에는 제대로 작동하지만 여러 행 출력에 대해서는 내가 잘못하고있는 것을 알 수 없습니다. 나는이 프로그램을 실행할 때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 

예를 들어 내가 "무료"명령을 사용하여 메모리 사용을 확인하지만 그것은 단지 여기에 라인 1과 3을 반환 들어 내 코드입니다 클라이언트 코드 :

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

이 답변은 정확합니다. 'line = 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에 데이터를 할당 할 경우 6,는

output = output + line;

1

나는 의견에 추가 다시 지적한다 .. while 루프 내부에서이 작업을 수행. readline()을 두 번 사용하면 stdout/stderr를 동시에 소비해야합니다. 그렇지 않으면 프로세스 출력을 소비하지 않으므로 프로세스 출력을 차단할 위험이 있습니다. 자세한 내용은 this SO answer을 참조하십시오.