0
private void readIncomingMessage() {
    try {
        StringBuilder builder = new StringBuilder();
        InputStream is = socket.getInputStream();
        int length = 1024;
        byte[] array = new byte[length];
        int n = 0;

        while ((n = is.read(array, n, 100)) != -1) {
            builder.append(new String(array));

            if (checkIfComplete(builder.toString())) {
                buildListItems(builder.toString(), null);
                builder = new StringBuilder();
            }
        }

    } catch (IOException e) {
        Log.e("TCPclient", "Something went wrong while reading the socket");
    }
}

你好,

我想读取每块 100 个字节的流,将这些字节转换为字符串,然后查看该字符串是否符合某些条件。

但是当我调试时,我看到构建器的计数为 3072。
我看到一个字符串,如 (text, , , , , , , , , , text , , , , , , , , , text)
我怎样才能添加给字符串生成器的文本?

谢谢 :)

 private void readIncomingMessage() {
    try {
        StringBuilder builder = new StringBuilder();
        InputStream is = socket.getInputStream();
        int length = 100;
        byte[] array = new byte[length];
        int n = 0;

        while ((n = is.read(array, 0, length)) != -1) {
            builder.append(new String(array, 0, n));

            if (checkIfComplete(builder.toString())) {
                buildListItems(builder.toString(), null);
                builder = new StringBuilder();
            }
        }

    } catch (IOException e) {
        Log.e("TCPclient", "Something went wrong while reading the socket");
    }
}

这个解决方案对我有用。这个解决方案有什么缺点吗?

4

2 回答 2

2

2个问题:

  1. 'n'将字节转换为字符串时需要使用该值。具体来说,使用这个 String 构造函数String(byte[] bytes, int offset, int length)
  2. 在将字节转换为任意边界上的字符串时,就像您正在做的那样,您有可能破坏多字节字符。如果和读取字符,你最好把它InputStreamReader放在上面。'is'
于 2012-07-12T14:59:54.680 回答
1

有关更多信息,请阅读文档read(byte[], int, int)new String(byte[])以及new String(byte[], int, int)

n 将保存上次读取操作中读取的字节数 - 而不是读取的字节数。如果您一次只想读取最多 100 个字节,则不需要大小为 1024 的字节数组,100 就可以了。当你从一个字节数组创建一个字符串时,它会使用整个数组(即使只有一半能够通过读取来填充),除非你告诉它你想使用数组的哪些部分。像这样的东西应该可以工作,但是您仍然可以进行改进:

private void readIncomingMessage() {
  try {
    StringBuilder builder = new StringBuilder();
    InputStream is = socket.getInputStream();
    int length = 100;
    byte[] array = new byte[length];
    int pos = 0;
    int n = 0;

    while (pos != length && ((n = is.read(array, pos, length-pos)) != -1)) {
        builder.append(new String(array, pos, n));
        pos += n;
        if (checkIfComplete(builder.toString())) {
            buildListItems(builder.toString(), null);
            builder = new StringBuilder();
            pos = 0;
        }
    }

} catch (IOException e) {
    Log.e("TCPclient", "Something went wrong while reading the socket");
}

}

于 2012-07-12T15:08:47.977 回答