Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/344.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/amazon-s3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java BufferedOutputStream写入垃圾数据_Java_Servlets_Download_Stream - Fatal编程技术网

Java BufferedOutputStream写入垃圾数据

Java BufferedOutputStream写入垃圾数据,java,servlets,download,stream,Java,Servlets,Download,Stream,我正在编写下载servlet,它读取html文件并写入servletOutputStream,文件传输的问题是添加了一些垃圾数据。对此有何建议 下面是我使用的代码 bis.read返回读取的字节数。您需要在write调用中考虑到这一点 比如: int rd; while ((rd=bis.read(...)) != -1) { bos.write(..., rd); } 问题在于代码的以下部分: while ((bis.read(barray, 0, BUFFER_

我正在编写下载servlet,它读取html文件并写入
servletOutputStream
,文件传输的问题是添加了一些垃圾数据。对此有何建议

下面是我使用的代码



bis.read
返回读取的字节数。您需要在
write
调用中考虑到这一点

比如:

int rd;
while ((rd=bis.read(...)) != -1) {
     bos.write(..., rd);
}

问题在于代码的以下部分:

        while ((bis.read(barray, 0, BUFFER_SIZE)) != -1) {
            bos.write(barray, 0, BUFFER_SIZE);
        }
即使输入的大小不是
缓冲区大小的倍数
,您也总是要写出
缓冲区大小的倍数。这将导致在最后一个块的末尾写入垃圾

您可以这样修复它:

        int read;
        while ((read = bis.read(barray, 0, BUFFER_SIZE)) != -1) {
            bos.write(barray, 0, read);
        }

如果你找到这个答案作为解决方案。。把它标对。
        int read;
        while ((read = bis.read(barray, 0, BUFFER_SIZE)) != -1) {
            bos.write(barray, 0, read);
        }