gpt4 book ai didi

java - 从输入流读取并添加到 stringbuilder

转载 作者:行者123 更新时间:2023-12-02 00:18:36 25 4
gpt4 key购买 nike

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 字节 block 的流,将这些字节转换为字符串,然后查看该字符串是否符合某些条件。

但是当我调试时,我看到构建器的计数为 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");
}
}

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

最佳答案

2个问题:

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

关于java - 从输入流读取并添加到 stringbuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11454591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com