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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:00:44  来源:igfitidea点击:

Java InputStream to ByteBuffer

javainputstreambytebuffer

提问by elect

I am reading dds textures, but since once built the jar I can't access those textures through urland fileand have to use InputStreaminstead.

我正在阅读 dds 纹理,但是自从构建了 jar 后,我就无法通过这些纹理访问这些纹理urlfile而必须InputStream改用。

So I would need to know how I can obtain a java.?nio.ByteBufferfrom an java.io.InputStream.

所以我需要知道如何java.?nio.ByteBufferjava.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 IOUtilstype has a static method to read an InputStreamand return a byte[].

IOUtils类型有一个静态方法来读取一个InputStream并返回一个byte[]

InputStream is;
byte[] bytes = IOUtils.toByteArray(is);

Internally this creates a ByteArrayOutputStreamand 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 InputStreamAPI which now includes InputStream::readAllBytesfunction, so no external libraries needed

JAVA 9 更新:如@saka1029所述,如果您使用的是 java 9+,则可以使用InputStream现在包含InputStream::readAllBytes函数的默认API ,因此不需要外部库

InputStream is;
byte[] bytes = is.readAllBytes()