Java File Read via ByteBuffer readFile(String name)

Here you can find the source of readFile(String name)

Description

Reads an array of bytes from a file.

License

Open Source License

Parameter

Parameter Description
name The name of the file.

Return

The read bytes.

Declaration

public static byte[] readFile(String name) throws Exception 

Method Source Code

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

import java.io.RandomAccessFile;

import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;

public class Main {
    /**//from  w w w .  j av a  2 s.co m
     * Reads an array of bytes from a file.
     * 
     * @param name
     *            The name of the file.
     * 
     * @return The read bytes.
     */
    public static byte[] readFile(String name) throws Exception {
        try (RandomAccessFile e = new RandomAccessFile(name, "r")) {
            MappedByteBuffer buf = e.getChannel().map(MapMode.READ_ONLY, 0L, e.length());

            byte[] data;
            if (buf.hasArray()) {
                data = buf.array();
                return data;
            }

            byte[] array = new byte[buf.remaining()];
            buf.get(array);
            data = array;
            return data;
        }
    }
}

Related

  1. readFile(String filename)
  2. readFile(String filename)
  3. readFile(String fileName)
  4. readFile(String filename)
  5. readFile(String filePath)
  6. readFile(String name)
  7. readFile(String path)
  8. readFile(String path)
  9. readFile(String path)