Java InputStream到ByteBuffer [英] Java InputStream to ByteBuffer
问题描述
我正在阅读dds纹理,但是一旦构建了jar,我无法通过 url
和文件$ c $访问这些纹理c>并且必须使用
InputStream
。
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.
所以我需要知道如何获得 java.nio.ByteBuffer
来自 java.io.InputStream
。
So I would need to know how I can obtain a java.nio.ByteBuffer
from an java.io.InputStream
.
Ps:无论通过第三方库,我只需要它工作
Ps: no matter through 3rd part libraries, I just need it working
推荐答案
在这种情况下,我最好的是 Apache commons-io 来处理这个和类似的任务。
For me the best in this case is Apache commons-io to handle this and similar tasks.
IOUtils
类型有一个静态方法来读取 InputStream
和返回 byte []
。
The IOUtils
type has a static method to read an InputStream
and return a byte[]
.
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
在内部创建 ByteArrayOutputStream
并复制字节到输出,然后调用 toByteArray()
。
Internally this creates a ByteArrayOutputStream
and copies the bytes to the output, then calls toByteArray()
.
UPDATE :只要你有字节数组
,就像 @Peter 指出,你必须转换为 ByteBuffer
UPDATE: as long as you have the byte array
, as @Peter pointed, you have to convert to ByteBuffer
ByteBuffer.wrap(bytes)
JAVA 9更新:如所述@ saka1029 如果您使用的是java 9+,则可以使用默认的 InputStream
API,现在包含 InputStream :: readAllBytes
函数,所以不需要外部库
JAVA 9 UPDATE: as stated by @saka1029 if you're using java 9+ you can use the default InputStream
API which now includes InputStream::readAllBytes
function, so no external libraries needed
InputStream is;
byte[] bytes = is.readAllBytes()
这篇关于Java InputStream到ByteBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!