gpt4 book ai didi

java - InputStream.read(byte[], 0 length) 提前停止?

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:23 25 4
gpt4 key购买 nike

我一直在写一些东西来从传入的 HttpServletRequest(下面的“请求”)读取请求流(包含 gzip 数据),但是看起来正常的 InputStream 读取方法实际上并没有读取所有内容?

我的代码是:

InputStream requestStream = request.getInputStream();
if ((length = request.getContentLength()) != -1)
{
received = new byte[length];
requestStream.read(received, 0, length);
}
else
{
// create a variable length list of bytes
List<Byte> bytes = new ArrayList<Byte>();

boolean endLoop = false;
while (!endLoop)
{
// try and read the next value from the stream.. if not -1, add it to the list as a byte. if
// it is, we've reached the end.
int currentByte = requestStream.read();
if (currentByte != -1)
bytes.add((byte) currentByte);
else
endLoop = true;
}
// initialize the final byte[] to the right length and add each byte into it in the right order.
received = new byte[bytes.size()];
for (int i = 0; i < bytes.size(); i++)
{
received[i] = bytes.get(i);
}
}

我在测试期间发现,有时顶部部分(当存在内容长度时)会停止读取传入请求流的一部分,并将“已接收”字节数组的其余部分留空。如果我只是让它始终运行 if 语句的 else 部分,它读起来很好,所有预期的字节都放在“已接收”中。

所以,似乎我现在可以通过这种更改让我的代码单独存在,但是有没有人知道为什么正常的“read”(byte[], int, int)”方法停止读取?描述说,如果存在文件末尾,它可能会停止。会不会是 gzip 压缩后的数据恰好包含与签名匹配的字节?

最佳答案

您需要在顶部添加一个while 循环来获取所有字节。流将尝试读取尽可能多的字节,但不需要立即返回 len 个字节:

An attempt is made to read as many as len bytes, but a smaller number may be read, possibly zero.

if ((length = request.getContentLength()) != -1)
{
received = new byte[length];
int pos = 0;
do {
int read = requestStream.read(received, pos, length-pos);

// check for end of file or error
if (read == -1) {
break;
} else {
pos += read;
}
} while (pos < length);
}

编辑:修复了。

关于java - InputStream.read(byte[], 0 length) 提前停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11937891/

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