Write an InputStream to an HttpServletResponse

前端 未结 3 1449
一个人的身影
一个人的身影 2020-12-03 07:02

I have an InputStream that I want written to a HttpServletResponse. There\'s this approach, which takes too long due to the use of byte[]

InputStream is = ge         


        
3条回答
  •  感动是毒
    2020-12-03 07:57

    I think that is very close to the best way, but I would suggest the following change. Use a fixed size buffer(Say 20K) and then do the read/write in a loop.

    For the loop do something like

    byte[] buffer=new byte[20*1024];
    outputStream=response.getOutputStream();
    while(true) {
      int readSize=is.read(buffer);
      if(readSize==-1)
        break;
      outputStream.write(buffer,0,readSize);
    }
    

    ps: Your program will not always work as is, because read don't always fill up the entire array you give it.

提交回复
热议问题