例如,如果我将多行分配给一个字符串,如下所示:
while ((line = reader.readLine()) != null)
{
output += line + "\n";
}
我是否可以将带有行分隔符的输出作为一个字符串返回?
我正在编写一个具有客户端和服务器程序的 Socket 程序,其中客户端向服务器发送请求,服务器以字符串的形式将该请求返回给客户端,但有些字符串是多行的。
服务器程序代码(部分代码):
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);
}
Client程序中的fromServer是Server程序的输出。这对于一行的输出效果很好,但如果它是多行,我无法弄清楚如何一次打印所有内容。
因此,如果输出例如等于:
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: