Java File Read via ByteBuffer readData(String fileName, int size)

Here you can find the source of readData(String fileName, int size)

Description

read Data

License

Open Source License

Declaration

public final static byte[] readData(String fileName, int size)
            throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

public class Main {
    public final static byte[] readData(String fileName, int size)
            throws IOException {

        final RandomAccessFile fis = new RandomAccessFile(fileName, "r");
        final FileChannel fc = fis.getChannel();
        if (size < 0) {
            size = (int) fc.size();
        }//from   w  w  w.  j  av  a  2  s. c om
        MappedByteBuffer buf = fc.map(MapMode.READ_ONLY, 0, size);
        final byte[] bytes = new byte[size];
        buf.get(bytes);
        fc.force(true);

        fis.close();
        closeDirectBuffer(buf);

        return bytes;
    }

    @SuppressWarnings("restriction")
    public static void closeDirectBuffer(ByteBuffer cb) {
        if (!cb.isDirect())
            return;
        try {
            ((sun.nio.ch.DirectBuffer) cb).cleaner().clean();
        } catch (Exception ex) {
        }
        cb = null;
    }
}

Related

  1. readBytes(String file)
  2. readCode(byte[] message)
  3. readColumnarKeyBlockDataForNoDictionaryCols(byte[] columnarKeyBlockData)
  4. readContent(File file)
  5. readContentsNIO(FileInputStream input, String encoding, boolean decodeNIO)
  6. readDelimitedFromInputStream(InputStream inputStream)
  7. readDouble(BufferedReader br, double[] buf)
  8. readDouble(byte[] src, int pointer)
  9. readDouble(FileChannel fileChannel, ByteOrder byteOrder)