单个String可以包含多行吗?

时间:2012-09-10 19:14:15

标签: java

例如,如果我将多行分配给字符串:

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

我是否可以将带有行分隔符的输出作为一个字符串返回?

我正在编写一个具有客户端和服务器程序的Socket程序,其中客户端向服务器发送请求,服务器以String的形式将该请求返回给客户端,但是一些String是多行。

服务器程序代码(代码的一部分):

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
Two
Three
Four

它返回如下:

One
Enter your choice:  (It prompts me for new command)
Two
Enter your choice:
Three
Enter your choice:
Four

所以它基本上打印了一行,问我新的选择并且无关紧要我输入它打印第二行,然后是第三行等等直到它到达最后一行,而不是像这样打印:

One
Two
Three
Four
Enter your choice:

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

为什么不将它移到while循环之外?

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