Java InputStream 到 ByteBuffer
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30026060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java InputStream to ByteBuffer
提问by elect
I am reading dds textures, but since once built the jar I can't access those textures through url
and file
and have to use InputStream
instead.
我正在阅读 dds 纹理,但是自从构建了 jar 后,我就无法通过这些纹理访问这些纹理url
,file
而必须InputStream
改用。
So I would need to know how I can obtain a java.?nio.ByteBuffer
from an java.io.InputStream
.
所以我需要知道如何java.?nio.ByteBuffer
从java.io.InputStream
.
Ps:no matter through 3rd part libraries, I just need it working
Ps:无论通过第 3 部分库,我只需要它工作
采纳答案by Jordi Castilla
For me the best in this case is Apache commons-ioto handle this and similar tasks.
对我来说,在这种情况下最好的是Apache commons-io来处理这个和类似的任务。
The IOUtils
type has a static method to read an InputStream
and return a byte[]
.
该IOUtils
类型有一个静态方法来读取一个InputStream
并返回一个byte[]
。
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
Internally this creates a ByteArrayOutputStream
and copies the bytes to the output, then calls toByteArray()
.
这会在内部创建 aByteArrayOutputStream
并将字节复制到输出,然后调用toByteArray()
.
UPDATE: as long as you have the byte array
, as @Peterpointed, you have to convert to ByteBuffer
更新:只要你有byte array
,正如@Peter指出的,你必须转换为ByteBuffer
ByteBuffer.wrap(bytes)
JAVA 9 UPDATE: as stated by @saka1029if you're using java 9+ you can use the default InputStream
API which now includes InputStream::readAllBytes
function, so no external libraries needed
JAVA 9 更新:如@saka1029所述,如果您使用的是 java 9+,则可以使用InputStream
现在包含InputStream::readAllBytes
函数的默认API ,因此不需要外部库
InputStream is;
byte[] bytes = is.readAllBytes()