gpt4 book ai didi

java - 从 ByteArrayOutputStream 修剪填充

转载 作者:行者123 更新时间:2023-12-01 23:40:59 25 4
gpt4 key购买 nike

我正在使用 Amazon S3,并且想要上传一个 InputStream(这需要计算我发送的字节数)。

public static boolean uploadDataTo(String bucketName, String key, String fileName, InputStream stream) {

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1];

try {
while (stream.read(buffer) != -1) { // copy from stream to buffer
out.write(buffer); // copy from buffer to byte array
}
} catch (Exception e) {
UtilityFunctionsObject.writeLogException(null, e);
}

byte[] result = out.toByteArray(); // we needed all that just for length
int bytes = result.length;
IO.close(out);
InputStream uploadStream = new ByteArrayInputStream(result);

....

}

有人告诉我一次复制一个字节的效率非常低(对于大文件来说很明显)。我不能做得更多,因为它会向 ByteArrayOutputStream 添加填充,而我无法删除它。我可以将其从结果中删除,但是如何安全地做到这一点呢?如果我使用 8KB 缓冲区,我可以去掉最右边的 buffer[i] == 0 吗?或者有更好的方法来做到这一点吗?谢谢!

在 Windows 7 x64 上使用 Java 7。

最佳答案

你可以这样做:

int read = 0;
while ((read = stream.read(buffer)) != -1) {
out.write(buffer, 0, read);
}

stream.read() 返回已写入buffer 的字节数。您可以将此信息传递给 out.write()len 参数。因此,请确保只写入从流中读取的字节。

关于java - 从 ByteArrayOutputStream 修剪填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17955312/

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