ServletOutputStream.write 有时会抛出索引越界
我遇到了一个无法一致重现的问题。我读取一个文件并将该文件的内容写入 ServletOutputStream。
byte[] buff = new byte[65536];
int bytesRead = dataStream.read(buff);
response.getOutputStream().write(buff, 0, bytesRead);
我注意到一些文件(小于 20KB)有时在写入输出流时抛出 IndexOutofBoundsException,但在其他时候,一切正常。我的意思是,没有报告 IndexOutOfBoundsException。
这是我得到的堆栈跟踪:
java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:331)
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:392)
at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:381)
at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:88)
at com.abc.web.DeliverData.serviceRequest(DeliverData.java:101)
我的代码中的第 101 行是: response.getOutputStream().write(buff, 0, bytesRead);
有什么想法为什么即使使用相同的文件进行测试也不能一致地报告问题?
I am having a problem which I cannot reproduce consistently. I read a file and write the contents of that file to ServletOutputStream.
byte[] buff = new byte[65536];
int bytesRead = dataStream.read(buff);
response.getOutputStream().write(buff, 0, bytesRead);
I noticed the some files (smaller than 20KBs) throw IndexOutofBoundsException when writing to the outputstream sometimes but at other times, everything works just find. By that I mean, no IndexOutOfBoundsException is reported.
Here is the stack trace that I get:
java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:331)
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:392)
at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:381)
at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:88)
at com.abc.web.DeliverData.serviceRequest(DeliverData.java:101)
Line 101 in my code is:
response.getOutputStream().write(buff, 0, bytesRead);
Any ideas why the problem is not reported consistently even if testing with the same files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
inputStream.read(..)
可以返回-1
。我建议使用IOUtils
来自commons-io:
IOUtils.copy(inputStream,outputStream)
。特此声明,具体实施如下:inputStream.read(..)
can return-1
. I'd suggest usingIOUtils
from commons-io:IOUtils.copy(inputStream, outputStream)
. For the record, it is implemented as follows: