ByteBuffer to File - Java java.nio

Java examples for java.nio:ByteBuffer File

Description

ByteBuffer to File

Demo Code


//package com.java2s;

import java.io.File;
import java.io.IOException;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static void toFile(ByteBuffer buffer, File file)
            throws IOException {
        RandomAccessFile raf = null;
        FileChannel channel = null;
        try {/*from   www.  j  a  v a 2  s.co  m*/
            raf = new RandomAccessFile(file, "rw");
            channel = raf.getChannel();
            channel.write(buffer);
            channel.force(false /*metadata*/);
            channel.close();
            raf.close();
        } finally {
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    // Ignored.
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    // Ignored.
                }
            }
        }
    }
}

Related Tutorials