ByteBuffer

Write/Append to File with ByteBuffer

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: March 19th, 2019
1 1,669 1 minute read

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 aFile 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 theallocateDirect(int) API method of theByteBuffer class
  • We create anInputStream 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 aFileChannel for the destination file and use thewrite(ByteBuffer) API method of the FileChannel instance providing the ByteBuffer as the input attribute

as described in the code snippet below.

Want to be a Java NIO Master ?
Subscribe to our newsletter and download the JDBCUltimateGuideright now!
In order to help you master Java NIO Library, we have compiled a kick-ass guide with all the major Java NIO features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.


 
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 fileboolean 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 channelchannel.close();}catch (IOException e) {System.out.println("I/O Error: " + e.getMessage());}}}
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ilias TsagklisIlias TsagklisNovember 11th, 2012Last Updated: March 19th, 2019
1 1,669 1 minute read
Photo of Ilias Tsagklis

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.