Java ByteBuffer load from File

Description

Java ByteBuffer load from File



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 main(String[] argv) throws Exception {
        File file = new File("Main.java");
        System.out.println(fromFile(file));
    }/*from ww w  .j a  va 2  s  .  co m*/

    public static ByteBuffer fromFile(File file) throws IOException {
        RandomAccessFile raf = null;
        FileChannel channel = null;
        try {
            raf = new RandomAccessFile(file, "r");
            channel = raf.getChannel();
            return channel.map(FileChannel.MapMode.READ_ONLY, 0,
                    file.length()).load();
        } finally {
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException e) {
                    // Ignored.
                }
            }
            if (raf != null) {
                try {
                    raf.close();
                } catch (IOException e) {
                    // Ignored.
                }
            }
        }
    }
}



PreviousNext

Related