从inputstream读取并添加到stringbuilder

时间:2012-07-12 14:54:33

标签: java inputstream stringbuilder

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 我看到一个字符串(文字,,,,,,,,,,文字,,,,,,,,,,文字)
我怎样才能将文本添加到stringbuilder?

thx:)

 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");
    }
}

这个解决方案对我有用。 这个解决方案的任何缺点?

2 个答案:

答案 0 :(得分:2)

2个问题:

  1. 在将字节转换为String时需要使用'n'值。具体来说,使用此String构造函数String(byte[] bytes, int offset, int length)
  2. 将字节转换为任意边界上的字符串时,就像您正在做的那样,您可能会损坏多字节字符。如果InputStreamReader并从中读取字符,最好将'is'放在首位。

答案 1 :(得分:1)

有关详情,请参阅read(byte[], int, int)new String(byte[])new String(byte[], int, int)

的文档

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

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");
}

}