当前位置: 首页 > 知识库问答 >
问题:

InputStream.Read(Byte[],0长度)提前停止?

胡玉书
2023-03-14
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);
    }
}

共有1个答案

戚令秋
2023-03-14

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

尝试读取多达len字节,但可能读取更小数目,可能为零。

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

编辑:修复时。

 类似资料:
  • 问题内容: 从InputStreams读取时,如何确定byte []使用什么大小? 什么时候使用小号vs大号?有什么区别?该数字是否要以1024为增量?如果它是网络vs磁盘的InputStream,是否会有区别? 非常感谢,我似乎在其他地方找不到明确的答案。 问题答案: 大多数人使用2的幂作为大小。如果缓冲区至少为512字节,则差异不大(<20%) 对于网络,最佳大小可以为2 KB至8 KB(基础

  • 问题内容: 如果存在连接/代理错误,我正在尝试重试请求。由于某些原因,我不断收到此错误,无论尝试重试该请求,该错误似乎都无法恢复: 难道我做错了什么?我的第一个怀疑是http.Request以某种方式被消耗了,因此在下一次尝试中它不再是好东西。我应该管理副本吗? 问题答案: 问题在于在第一次调用Do()时将请求主体读到末尾。在随后对Do()的调用中,没有从响应主体读取任何数据。 解决方法是将主体阅

  • 我尝试将元素映射到[]以获得角度。但如果我检查了对象的长度,则始终为0。。 屏幕如果I控制台.log(对象) 我做错了什么?

  • 这就是我得到的: DOMNodeList对象([长度]=>0)

  • 我使用的是一个3D数组,下面的代码是我得到的数组索引超出界限的错误,下面是相同的代码:- 获取以下错误:- 线程“main”Java.lang.ArrayIndexOutOfBoundsException中出现异常:索引0超出了Array2d.TugasArray3.Main(TugasArray3.:27)得分Mid Test1 Ke-1

  • 百度提前批(凉面) 7月17百度Java工程师-移动生态数据研发部。 先介绍了一下简历中的项目,没深入细问。 面试问题: 1. Java内存,越详细越好(答了一点点) 2. transient关键字(电脑声音小,没听清) 3. 集合用了哪些?(hashmap 引出 cocurrenthashmap 答完了) 4. volatile 和synchronized 区别(答完了) 5. 内部类和嵌套类之