0

I'm trying to write the contents of a byte buffer to a file, using the offset (position). It works when I convert to an input stream, but not when I wrap in a new ByteBuffer

This works:

new ByteArrayInputStream(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())

This doesn't

ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())

More specifically, when I say it doesn't work, writing the contents of the buffer to a file:

Files.write(path, ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position()).array())

results in bytes written to the file but it is not complete, so the jpeg cannot be viewed, but if I write the same buffer, wrapping in a ByteArrayInputStream, it does work:

val in = new ByteArrayInputStream(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())
Iterator.continually (in.read).takeWhile (-1 != _).foreach (fileOutputStream.write)

So I must be doing something silly and perhaps I don't understand how ByteBuffer works

Andrew
  • 716
  • 1
  • 8
  • 19

1 Answers1

2

ByteBuffer.wrap(byteBuffer.array(), <ANYTHING>, <ANYTHING>).array() means just byteBuffer.array(), and <ANYTHING> isn't taken into account.

Also, the whole

ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())

is just a cumbersome way to create a shallow copy of byteBuffer, why do you do it instead of just using the byteBuffer itself?

Looks like what you want is something like

try (FileChannel outCh = new FileOutputStream(filename).getChannel()) {
    outCh.write(byteBuffer);
}
starikoff
  • 1,601
  • 19
  • 23
  • Your suggestion works but I'm still curious how to make it work with something like Files.write, which takes a byte array. Some apis I'm working with only take a byte array – Andrew Oct 23 '17 at 19:06
  • 1
    You have to manually copy the correct part of the array, see e.g. here https://stackoverflow.com/a/679325/2369544. Also a suggestion that it sort of contradicts the philosophy behind the ByteBuffer and you should only do it as a last resort: https://stackoverflow.com/a/679335/2369544. – starikoff Oct 23 '17 at 19:13