4

我想读取所有数据,同步,从客户端或服务器接收没有readline()java中的方法(如readall()c++)。
我不想使用下面的代码:

BufferedReader reader = new BufferedReader(new inputStreamReader(socket.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null)
     document.append(line + "\n");

我应该使用什么方法?

4

3 回答 3

6

如果您知道传入数据的大小,则可以使用以下方法:

public int read(char cbuf[], int off, int len) throws IOException;

其中 cbuf 是目标缓冲区。

否则,您将不得不读取行或读取字节。流不知道传入数据的大小。只能按顺序读取,直到到达结束(读取方法返回 -1)

参考这里流文档

像这样的东西:

public static String readAll(Socket socket) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null)
        sb.append(line).append("\n");
    return sb.toString();
}
于 2013-07-12T12:04:28.253 回答
1

你可以使用这样的东西:

   public static String readToEnd(InputStream in) throws IOException {
      byte[] b = new byte[1024];
      int n;
      StringBuilder sb = new StringBuilder();
      while ((n = in.read(b)) >= 0) {
         sb.append(b);
      }
      return sb.toString();
   }
于 2014-01-09T10:56:55.273 回答
0

尝试这个

public static String readToEnd(InputStream in) throws IOException {
    return new String(in.readAllBytes(),StandardCharsets.UTF_8);
}
于 2022-02-22T16:55:21.027 回答