ByteBuffer

Write/Append to File with ByteBuffer

With this is example we are going to demonstrate how to write/append data to a file in Java using a ByteBuffer. Particularly we are going to read data from a source file and append them to the destination file. In short what we do is the following :

  • Create a File object to encapsulate an actual file in the file system that we want to read data from
  • Allocate a direct (memory-mapped) byte buffer with a byte capacity equal to input file’s length. To do so we use the allocateDirect(int) API method of the ByteBuffer class
  • We create an InputStream of the source file so as to read data and put them in the newly created ByteBuffer
  • In order to append the data in the ButeBuffer to the destination file all we have to do is create a FileChannel for the destination file and use the write(ByteBuffer) API method of the FileChannel instance providing the ByteBuffer as the input attribute

as described in the code snippet below.


 
Do not forget to close the channel after you are done processing the file so as to release operating system resources.

package com.javacodegeeks.snippets.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class WriteAppendToFileWithByteBuffer {

	public static void main(String[] args) {

		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 use this approach for copying large files
		    ByteBuffer buf = ByteBuffer.allocateDirect((int)inFile.length());

			InputStream is = new FileInputStream(inFile);

		    int b;

		    while ((b=is.read())!=-1) {
		    	buf.put((byte)b);
		    }

			File file = new File("out.xml");

			// append or overwrite the file
			boolean append = false;

			FileChannel channel = new FileOutputStream(file, append).getChannel();

			// Flips this buffer.  The limit is set to the current position and then
			// the position is set to zero.  If the mark is defined then it is discarded.
			buf.flip();

			// Writes a sequence of bytes to this channel from the given buffer.
			channel.write(buf);

			// close the channel
			channel.close();

		}
		catch (IOException e) {
			System.out.println("I/O Error: " + e.getMessage());
		}

	}

}

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Virak
Virak
3 years ago

Do you know how to write ByteBuffer audio to wav file?

Back to top button