ByteBuffer from File - Java java.nio

Java examples for java.nio:ByteBuffer File

Description

ByteBuffer from 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 main(String[] argv) throws Exception {
        File file = new File("Main.java");
        System.out.println(fromFile(file));
    }//from  www. ja  v  a  2  s  .  c om

    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.
                }
            }
        }
    }
}

Related Tutorials