How to Write InputStream to RandomAccessFile

4 years ago by in How To, IO Tagged: , , ,

Writing an InputStream (Java Doc) to a RandomAccessFile (Java Doc) is quite simple as shown in the following example. This example also makes use of FileLock (Java Doc) to make sure that no one modifies the file while the data is being written to file.


import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.ReadableByteChannel;

public class Example {
  public static void main(final String[] args) throws IOException {
    final File outputFile = new File("");
    try (RandomAccessFile raf = new RandomAccessFile(outputFile, "rw"); FileChannel fc = raf.getChannel();) {
      final FileLock fl = fc.tryLock();
      if (fl == null) {
        // Failed to acquire lock
      } else {
        try (final ReadableByteChannel in = Channels.newChannel(new BufferedInputStream(Example.class
            .getResourceAsStream("/")))) {
          for (final ByteBuffer buffer = ByteBuffer.allocate(1024); != -1;) {
        } finally {

This example also makes use of ByteBuffer (Java Doc) to store the data read from the InputStream and then written to the file.

Albert Attard

Albert Attard is a Java passionate and technical lead at a research group. You can find him on . Over the past years Albert worked on various Java projects including traditional server/client applications, modular applications, large data handling applications and concurrent data manipulation applications to name a few. He has a BSc degree from the University of London (Homepage) and an MSc Information Security with the same university. His MSc thesis (Book) received the 2012 award (Website).

Leave a Comment

Time limit is exhausted. Please reload the CAPTCHA.