3

I've got a bunch of float data in a FloatBuffer which needs to be written to a file (without it taking three minutes). Currently a DataOutputStream is used to write the FloatBuffer element by element to a file. This is slow. Preferably, I'd like to be using a FileChannel, but I hit a snag since it seems a FloatBuffer can't be converted to a ByteBuffer and bytes are what the FileChannel needs in order to write data.

Instead of using FoatBuffers as my data source, I could easily be using an array. But I can't easily use a ByteBuffer/array instead.

Any insight into this problem would be much appreciated. Thanks.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
user8709
  • 1,342
  • 13
  • 31

1 Answers1

4

Instead of starting off with a FloatBuffer, could you create a ByteBuffer to use for writing to the FileChannel, then use ByteBuffer.asFloatBuffer, write into that FloatBuffer however you're currently doing it, and then write out the ByteBuffer which will then contain the relevant information?

Personally I've always found java.nio rather confusing, but this feels like it probably should work...

EDIT: Another user tried this, and found it not to work:

However, asFloatBuffer() will not work because hasArray() will be false. In short, the following does not work (neither allocate, nor allocateDirect will work):

ByteBuffer.allocate(amount * 4).asFloatBuffer().asArray()

I don't have the time to investigate alternatives right now, unfortunately.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Ok, I forgot the ByteBuffer had a putFloat function. This works really well. Using a FileChannel is so very much faster. Thanks. – user8709 Jul 05 '11 at 20:40
  • @user756670: It has putFloat, but that's a single-shot operation. Using `asFloatBuffer` allows you to do bulk putting, which is probably better yet. – Jon Skeet Jul 05 '11 at 20:47
  • I have an external library that returns FloatBuffer object, so I cannot start with ByteBuffer. What do I do? – Aleksei Petrenko Jan 28 '17 at 16:44
  • @AlexPetrenko: See http://stackoverflow.com/questions/27492161/convert-floatbuffer-to-bytebuffer – Jon Skeet Jan 28 '17 at 20:12
  • I have no such method on my FloatBuffer. There are no methods that return ByteBuffer, I checked) I use Android. – Aleksei Petrenko Jan 28 '17 at 20:14
  • @AlexPetrenko: I edited my comment very shortly after writing it - did you check the referenced question? I suggest you ask a new question with more details - in particular that it's for Android - if that doesn't help you. – Jon Skeet Jan 28 '17 at 21:35