簡體   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