0

I'm trying to save ByteBuffers to a file:

        FileChannel fc = new FileOutputStream("file.something").getChannel();

        while(true) {
            ByteBuffer b = nalUnits.poll();

            System.out.println("gonna write " + b.capacity());
            //printByteBuffer(b);
            fc.write(b);
        }
        System.out.println("gonna close");
        fc.close();
        System.out.println("did close");


static void printByteBuffer(ByteBuffer b) {
    for (int k = 0; k < b.position(); k++) {
        System.out.print(b.get(k) + " ");
    }
    System.out.println();
}

I get this as output:

gonna write 41091
gonna write 41498
gonna write 41299
gonna write 40836
gonna write 40275
gonna write 40708
...
gonna close
did close

but the file has 0kb. If I uncomment "printBuffer", I can see all the buffers printed on screen, they're not empty. Why do I end up with an empty file?

user207421
  • 305,947
  • 44
  • 307
  • 483
Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 1
    Looks like you need to call `force()` on the `FileChannel` - see [Is FileChannel#force is equivalent to OutputStream#flush? Do I always have to call it?](https://stackoverflow.com/questions/34859380/is-filechannelforce-is-equivalent-to-outputstreamflush-do-i-always-have-to-ca) – RaffleBuffle May 15 '20 at 02:23
  • @SirRaffleBuffle `((FileChannel) fc).force(true);` didnt work. Putting `false` also didnt work – Guerlando OCs May 15 '20 at 02:47
  • You need to flip before write, and compact afterwards. See the Javadoc. – user207421 May 15 '20 at 02:57

0 Answers0