简体   繁体   English

如何使用BufferedReader读取多行?

[英]how to read multiple lines using BufferedReader?

I am sending a Text from Xcode (that a user enters on a textView) to java server. 我正在从Xcode(用户在textView上输入)发送文本到Java服务器。 the text may contain more than one line. 文本可能包含多行。 the problem is when receiving the text, only even lines are being read. 问题是在接收文本时,仅读取偶数行。 here is my code. 这是我的代码。

server: 服务器:

            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

client side: 客户端:

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

You're consuming three lines: 您消耗了三行:

  1. Check if there's next line 检查是否有下一行
  2. Printing line 印刷线
  3. Storing one. 存放一个。

Noted here: 在这里注明:

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

Store the line in a String and then do what you want/need with it: 将行存储在String ,然后执行您想要/需要的操作:

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

I think the issue is this: 我认为问题是这样的:

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

The issue, specifically, is the three readLine() calls. 具体来说,问题是三个readLine()调用。 Each call will read another line from the client . 每个呼叫将从客户端读取另一行 So effectively you're reading a line to check if the client has stuff to send, reading another line and printing printing it, then reading another and storing it. 因此,您正在有效地读取一行以检查客户端是否有要发送的内容, 读取另一行并进行打印打印, 然后读取另一行并进行存储。

What you want to do is store the read line in a temp variable, print it, then append it: 您要做的是将读取的行存储在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