Look at Channels.newChannel(OutputStream). It will give you a channel given an OutputStream. With the WritableByteChannel adapter you can provide the ByteBuffer which will write it to the OutputStream.

public void writeBuffer(ByteBuffer buffer, OutputStream stream) {
   WritableByteChannel channel = Channels.newChannel(stream);

   channel.write(buffer);
}

This should do the trick!

Answer from ng. on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 45724891 › java-write-bytes-from-bytebuffer-to-file-in-byte-format
android - Java write bytes from Bytebuffer to File in byte format - Stack Overflow
ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize); byteBuffer.put(hm.getDocID().getBytes()); byteBuffer.put(hm.getFextension().getBytes()); byteBuffer.put(hm.getMagic().getBytes()); byteBuffer.put(hm.getFversion().getBytes()); byteBuffer.put(hm.getFsize().getBytes()); byteBuffer.flip(); byte[] bablock = new byte[byteBuffer.remaining()]; BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(idHeader)); bos.write(bablock); bos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
🌐
Blogger
javarevisited.blogspot.com › 2016 › 01 › reading-writing-files-using-filechannel-bytebuffer-example.html
Reading/Writing to/from Files using FileChannel and ByteBuffer in Java - Example Tutorial
September 10, 2021 - Here is the step by step guide to starting reading data from a file using RandomAccessFile, FileChannel, and ByteBuffer: Open the file you want to read/write using RandomAccessFile in read/write mode.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java › nio › bytebuffer
Write/Append to File with ByteBuffer - Java Code Geeks
March 19, 2019 - Do not forget to close the channel ... { try { File inFile = new File("in.xml"); // Allocate a direct (memory-mapped) byte buffer with a byte capacity equal to file's length // DO NOT u...
🌐
Java2s
java2s.com › Tutorials › Java › IO_How_to › nio_Buffer › Save_ByteBuffer_to_a_file.htm
Java I/O How to - Save ByteBuffer to a file
Writer · XML Delete · Zip · Back to nio Buffer ↑ · We would like to know how to save ByteBuffer to a file. /*from ww w. ja v a2s .co m*/ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Main { private static final int BSIZE = 1024; public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text ".getBytes())); fc.close(); } } Back to nio Buffer ↑
🌐
Baeldung
baeldung.com › home › java › java io › writing byte[] to a file in java
Writing byte[] to a File in Java | Baeldung
December 11, 2025 - We’ll open an output stream to our destination file, and then we can simply pass our byte[] dataForWriting to the write method. Note that we’re using a try-with-resources block here to ensure that we close the OutputStream in case an IOException ...
🌐
Baeldung
baeldung.com › home › java › java io › guide to java filechannel
Guide to Java FileChannel | Baeldung
February 20, 2026 - In this quick tutorial, we’ll look at the FileChannel class provided in the Java NIO library. We’ll discuss how to read and write data using FileChannel and ByteBuffer.
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › nio › class-use › ByteBuffer.html
Uses of Class java.nio.ByteBuffer (Java SE 9 & JDK 9 )
Report a bug or suggest an enhancement For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples.
Find elsewhere
🌐
HappyCoders.eu
happycoders.eu › java › bytebuffer-flip-compact
Java ByteBuffer Example: How to use flip() + compact()
June 12, 2025 - In this article, I will show you, ... precisely. ... Let’s go! You need a ByteBuffer to write data to or read data from a file, a socket, or another I/O component using a so-called “Channel”....
🌐
Mkyong
mkyong.com › home › java › java – how to save byte[] to a file
Java - How to save byte[] to a file - Mkyong.com
September 17, 2020 - FileUtils.writeByteArrayToFile(new File("/path/file"), bytes); ... <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.7</version> </dependency> The below example reads a file and converts the data into ...
🌐
Vultr Docs
docs.vultr.com › java › examples › convert-file-to-byte-array-and-vice-versa
Java Program to Convert File to byte array and Vice-Versa | Vultr Docs
December 5, 2024 - Create a method to write the byte array to a file using NIO FileChannel. java Copy · import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Paths; import ...
🌐
HappyCoders.eu
happycoders.eu › java › filechannel-memory-mapped-io-locks
FileChannel, Memory-Mapped I/O, Locks (Java Files Tutorial)
November 29, 2024 - We do not read the entire buffer, but only a random number of bytes, and thus simulate that we cannot process the data completely. Then we switch back to buffer write mode with buffer.compact() and read more bytes from the FileChannel. For a better understanding, I recommend you read the article Java ByteBuffer: How to use flip() and compact().
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › › › java › nio › class-use › ByteBuffer.html
Uses of Class java.nio.ByteBuffer (Java Platform SE 7 )
Submit a bug or feature For further ... see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples. Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license ...
🌐
How to do in Java
howtodoinjava.com › home › i/o › writing byte[] to a file in java
Writing Byte[] to a File in Java
April 18, 2022 - The FileUtils class has method writeByteArrayToFile() that writes the byte array data into the specified file.
🌐
Baeldung
baeldung.com › home › java › java io › guide to bytebuffer
Guide to ByteBuffer | Baeldung
November 28, 2024 - To transfer byte data, the ByteBuffer class provides single and bulk operations. We can read or write a single byte from/to the buffer’s underlying data in single operations.
🌐
Novixys Software
novixys.com › blog › java-nio-using-bytebuffer
Java NIO - Using ByteBuffer | Novixys Software Dev Blog
March 24, 2017 - The FileChannel provides methods for reading from and writing to ByteBuffers. To begin with, we need a ByteBuffer to read and write data into.
Top answer
1 of 2
7

The reason why your file when written using the ByteBuffer is bigger is because of how you initialize the ByteBuffer. When you simply write using writeInt(int), you are writing only the data that you need to write. However, when you create your ByteBuffer, you create it larger than it needs to be to prevent overflow which I understand. However, that also means that the underlying array, the one returned from the array() method, is also larger than it needs to be. Since arrays don't understand positions and limits, when you write the array, all of the data and the empty space after that is written, causing the large file size. What you need to do is after putting all of your data inside the buffer, you need to flip the buffer and then create a new array with length the same as the limit() of the buffer (once flipped), and then get(byte[]) all of the data from the buffer. Once you have that array, you need to write it.

This is what I'm talking about:

try (RandomAccessFile out = new RandomAccessFile(file, "rw")) {
    ByteBuffer buffer = ByteBuffer.allocate(totalPkts*4);

    for(int i = 0; i < totalPkts; i++) {
        buffer.putInt(data.get(i));
    }

    buffer.flip();
    byte[] data = new byte[buffer.limit()];
    buffer.get(data);
    out.write(data);
}
2 of 2
0

If you would like to reduce the amount of writes consider using a byte array to write to a file stream. (provided the data in data variable can be converted to bytes). As for not being the same please check if you are flushing the stream at some point and closing it properly before program termination.