gpt4 book ai didi

java - 从InputStream读取到OutputStream的最快方法

转载 作者:行者123 更新时间:2023-12-01 16:42:54 26 4
gpt4 key购买 nike

下面的代码以 1.3 秒的速度传输 2.43 MB 文件

byte[] buff = new byte[64*1024];

private static void flow(InputStream is, OutputStream os, byte[] buf )
throws IOException {
int numRead;
while ( (numRead = is.read(buf) ) >= 0) {
os.write(buf, 0, numRead);
}
}

InputStream“流”到OutputStream的最快方法是什么?

更新:

数据源是缓存,具体为EHCache:

byte[] cached = cacheService.get(cacheKey); // Just `2 ms` to get the bytes, very fast
if(cached != null && cached.length > 0) {
flow(ByteSource.wrap(cached).openStream(), outputStream, buff);
}

最佳答案

我无法断言它是最快的,但我建议使用 apache-commons-ioIOUtils。具体来说

public static long copy(InputStream input, OutputStream output, int bufferSize)

并尝试使用不同的 bufferSize 值进行基准测试。

https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/IOUtils.html#copy(java.io.InputStream,%20java.io.OutputStream,%20int)

这里真正的问题是您正在使用的高级抽象。如果您确切地知道数据来自哪里(例如文件系统)和要去哪里(例如网络套接字)并且您知道您正在使用哪个操作系统,则可以利用内核的流支持来实现这一点快点。

谷歌搜索“零复制内核io”我发现这篇文章是一个不错的概述: https://xunnanxu.github.io/2016/09/10/It-s-all-about-buffers-zero-copy-mmap-and-Java-NIO/

关于java - 从InputStream读取到OutputStream的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59939873/

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