2012-09-10 3 views
0

나는 그래서 문자열로 여러 줄을 지정하는 경우 :단일 문자열에 여러 줄이 포함될 수 있습니까? 예를 들어

while ((line = reader.readLine()) != null) 
     { 
      output += line + "\n"; 
     } 

그것은 나를 하나의 문자열로 라인 분리로 출력을 반환 할 수 있습니까?

클라이언트가 서버에 요청을 보내고 서버가 문자열 형식으로 요청을 클라이언트에 반환하지만 일부 문자열이 여러 줄인 클라이언트 및 서버 프로그램이있는 소켓 프로그램을 작성하고 있습니다.

서버 프로그램 코드 (코드의 일부)

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(); 
     } 

    } 

클라이언트 프로그램 코드 : 클라이언트 프로그램이

while ((fromServer = input.readLine())+"\n" != 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); 

     } 

fromServer 서버 프로그램으로부터 출력된다. 이것은 한 줄의 출력물에서 잘 작동하지만, 여러 줄이 있다면 한꺼번에 출력하는 방법을 알 수 없습니다.

그래서 예를 들어 출력이 동일한 경우 :

그래서 그것은 기본적으로 하나 개의 라인을 인쇄
One 
Enter your choice: (It prompts me for new command) 
Two 
Enter your choice: 
Three 
Enter your choice: 
Four 

, 새로운 선택을 올려주세요 내가 입력 중요하지 않습니다

One 
Two 
Three 
Four 

그것은이로 반환 다음과 같이 인쇄하는 대신 마지막 행에 도달 할 때까지 두 번째 줄, 세 번째 줄 등을 인쇄합니다.

One 
Two 
Three 
Four 
Enter your choice: 
+0

가능한 중복 : 내가 제대로 귀하의 요구 사항을 이해한다면

또한, 코드가 아래처럼 뭔가해야 [자바 여러 문자열 (http://stackoverflow.com/questions/878573/java-multiline -string) –

답변

0

왜 이것을 while 루프 외부로 옮기는 것이 좋을까요?

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

내가 할 때 그것은 무한 루프에서 계속 실행됩니다. – Nick

1

코드에 또 다른 실수가 있습니다 : while ((fromServer = input.readLine())+"\n" != null). 항상 사실입니다. 다음 사항 만 확인하십시오 : while ((fromServer = input.readLine()) != null).

String fromServer = ""; 
String line; 
while ((line = input.readLine()) != null) { 
    fromServer += line + "\n"; // collect multiline strings into fromServer 
} 

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); 
} 
+0

약간의 진전이 있었지만 코드에서 출력을 추가했습니다. – Nick

+0

내 코드에서 출력 한 "Enter your choice :"출력이 여러 번 인쇄됩니다. 그래서 위의 코드를 반복적으로 실행하고있는 것처럼 보입니다. –