繁体   English   中英

如何使用BufferedReader读取多行?

[英]how to read multiple lines using BufferedReader?

我正在从Xcode(用户在textView上输入)发送文本到Java服务器。 文本可能包含多行。 问题是在接收文本时,仅读取偶数行。 这是我的代码。

服务器:

            StringBuilder sb = new StringBuilder();
            while(inFromClient.readLine()!=null){   //infromClient is the buffered reader

                sb.append(inFromClient.readLine());
                sb.append('\n');
            }
            System.out.println ("------------------------------");
            System.out.println (sb.toString()); //the received text

客户端:

           NSString *notecontent=[NSString  stringWithFormat:@"%@",self.ContentTextView.text];
        NSData *notecontentdata = [[NSData alloc] initWithData:[notecontent dataUsingEncoding:NSASCIIStringEncoding]];
        [outputStream write:[notecontentdata bytes] maxLength:[notecontentdata length]];

您消耗了三行:

  1. 检查是否有下一行
  2. 印刷线
  3. 存放一个。

在这里注明:

while(inFromClient.readLine()!=null) { //1.
    System.out.println (inFromClient.readLine()); //2.
    sb.append(inFromClient.readLine()); //3.
    sb.append('\n');
}

将行存储在String ,然后执行您想要/需要的操作:

String line = "";
while ((line = inFromClient.readLine()) != null) {
    System.out.println(line);
    sb.append(line);
    sb.append('\n');
}

我认为问题是这样的:

while(inFromClient.readLine()!=null){   //infromClient is the buffered reader
    System.out.println (inFromClient.readLine());
    sb.append(inFromClient.readLine());
    sb.append('\n');
}

具体来说,问题是三个readLine()调用。 每个呼叫将从客户端读取另一行 因此,您正在有效地读取一行以检查客户端是否有要发送的内容, 读取另一行并进行打印打印, 然后读取另一行并进行存储。

您要做的是将读取的行存储在temp变量中,进行打印,然后附加它:

String s;
while((s = inFromClient.readLine()) !=null){   //infromClient is the buffered reader
    System.out.println (s);
    sb.append(s);
    sb.append('\n');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM