Java File Read via ByteBuffer readFile(File file)

Here you can find the source of readFile(File file)

Description

Reads the contents of the given File into a ByteBuffer.

License

Open Source License

Declaration

public static ByteBuffer readFile(File file) throws IOException 

Method Source Code


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

import java.io.*;
import java.nio.*;

public class Main {
    /**//from  www.  java 2  s. c  o m
     * Reads the contents of the given File into a ByteBuffer.
     * This ByteBuffer is always backed by a byte[] of exactly the file's length (at the time we started to read).
     */
    public static ByteBuffer readFile(File file) throws IOException {
        DataInputStream dataInputStream = null;
        try {
            // FIXME: this is broken for files larger than 4GiB.
            int byteCount = (int) file.length();

            // Always read the whole file in rather than using memory mapping.
            // Windows' file system semantics also mean that there's a period after a search finishes but before the buffer is actually unmapped where you can't write to the file (see Sun bug 6359560).
            // Being unable to manually unmap causes no functional problems but hurts performance on Unix (see Sun bug 4724038).
            // Testing in C (working on Ctags) shows that for typical source files (Linux 2.6.17 and JDK6), the performance benefit of mmap(2) is small anyway.
            // Evergreen actually searches both of those source trees faster with readFully than with map.
            // At the moment, then, there's no obvious situation where we should map the file.
            FileInputStream fileInputStream = new FileInputStream(file);
            dataInputStream = new DataInputStream(fileInputStream);
            final byte[] bytes = new byte[byteCount];
            dataInputStream.readFully(bytes);

            return ByteBuffer.wrap(bytes);
        } finally {
            dataInputStream.close();
        }
    }
}

Related

  1. readFile(File file)
  2. readFile(File file)
  3. readFile(File file)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(java.io.File file)
  7. readFile(String filename)
  8. readFile(String filename)
  9. readFile(String fileName)