我尝试使用偏移量(位置)将字节缓冲区的内容写入文件。它在我转换为输入流时有效,但在我换入新的ByteBuffer
时则无效这有效:
new ByteArrayInputStream(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())
这不是
ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())
更具体地说,当我说它不起作用时,将缓冲区的内容写入文件:
Files.write(path, ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position()).array())
导致写入文件的字节但是不完整,因此无法查看jpeg,但如果我编写相同的缓冲区,包装在ByteArrayInputStream中,它确实有效:
val in = new ByteArrayInputStream(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())
Iterator.continually (in.read).takeWhile (-1 != _).foreach (fileOutputStream.write)
所以我必须做些傻事,也许我不明白ByteBuffer是如何工作的
答案 0 :(得分:1)
ByteBuffer.wrap(byteBuffer.array(), <ANYTHING>, <ANYTHING>).array()
仅表示byteBuffer.array()
,并且<ANYTHING>
未被考虑在内。
另外,整个
ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())
只是创建byteBuffer
浅表副本的一种繁琐方式,为什么要这样做而不只是使用byteBuffer
本身?
看起来像你想要的是
try (FileChannel outCh = new FileOutputStream(filename).getChannel()) {
outCh.write(byteBuffer);
}