gpt4 book ai didi

tomcat - 应写入 ServletOutPutStream 的字节

转载 作者:行者123 更新时间:2023-11-28 22:45:42 36 4
gpt4 key购买 nike

我想知道在创建将内容写入 ServletOutputStream 的 byte[] 时是否有特定规则或最佳实践?

  byte[] buffer = new byte[1024];   
int r = 0;
try {
in = new BufferedInputStream(new FileInputStream(new File("/path/to/the/some/file")));
sos = response.getOutputStream();
while ((r = in.read(buffer, 0, buffer.length)) != -1) {
sos.write(buffer, 0, r);

在上面的代码中,byte[] lenth 是 1024。如果我在 tomcat 中运行我的 servlet,我是否需要将缓冲区的长度与 tomcat 缓冲区的长度相匹配?还是真的不重要? Tomcat 默认缓冲区大小可能是 4096 而我的 byte[] 可以说是 20000

不确定问题是否有意义,但自从我增加了代码中的 byte[] 长度后,我就遇到了 indexoutofboundsexception。之前 byte[] 的长度是 1Kb,我改成了 64kb,开始出现 indexoutofboundsexception

最佳答案

难道你不能忘记缓冲区和容易出错的循环并简单地调用:

IOUtils.copy(in, response.getOutputStream());

http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html

我知道这不是您问题的确切答案,但我更喜欢干净且防弹的代码,而不是有问题的优化。

关于tomcat - 应写入 ServletOutPutStream 的字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4936858/

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