Java File Read via ByteBuffer readFileAsByteArray(String path)

Here you can find the source of readFileAsByteArray(String path)

Description

This method reads file as binary data.

License

Open Source License

Parameter

Parameter Description
path String that contains the path to the file to be read

Exception

Parameter Description
IOException if any problem occurred

Return

byte array that contains the file content

Declaration

public static byte[] readFileAsByteArray(String path) throws IOException 

Method Source Code


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

import java.io.IOException;
import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.text.MessageFormat;

public class Main {
    private static final int MAX_READ_FAILURES = 10;

    /**// w  w w.j  ava2  s.  c  o m
     * This method reads file as binary data. It can read files that are no larger than 2147483647 bytes
     *
     * @param path String that contains the path to the file to be read
     * @return byte array that contains the file content
     * @throws IOException if any problem occurred
     */
    public static byte[] readFileAsByteArray(String path) throws IOException {
        return internalReadFileAsByteArray(path).array();
    }

    /**
     * This method that actually performs binary file content reading. It can read files that are no larger than 2147483647 bytes
     *
     * @param path String that contains the path to the file to be read
     * @return byte array that contains the file content
     * @throws IOException if any problem occurred
     */
    private static ByteBuffer internalReadFileAsByteArray(String path) throws IOException {
        ByteBuffer byteBuffer = null;
        Path filePath = FileSystems.getDefault().getPath(path);
        try (FileChannel fileChannel = FileChannel.open(filePath, StandardOpenOption.READ);) {
            Long size = fileChannel.size();
            if (size > Integer.MAX_VALUE) {
                throw new IOException(MessageFormat.format(
                        "File {0} is too large. Its size is {1,number,integer} bytes which is larger "
                                + "then this method could handle ( {2,number,integer})",
                        path, size, Integer.MAX_VALUE));
            }
            byteBuffer = ByteBuffer.allocate(size.intValue());
            int readBytes = 0;
            int totalReadBytes = 0;
            int failureCounter = 0;
            while ((readBytes = fileChannel.read(byteBuffer)) >= 0 && totalReadBytes < size.intValue()) {
                if (readBytes > 0) {
                    totalReadBytes += readBytes;
                    if (failureCounter > 0) {
                        failureCounter = 0;
                    }
                } else {
                    if (++failureCounter >= MAX_READ_FAILURES) {
                        throw new IOException(
                                MessageFormat.format("File {0} could not be read for unknown reason", path));
                    }
                }
            }
        }
        return (ByteBuffer) byteBuffer.flip();
    }
}

Related

  1. readFile(String path)
  2. readFile(String path)
  3. readFile(String path)
  4. readFile(String path)
  5. readFileAsByteArray(File file)
  6. readFileAsStringArray(File file)
  7. readFileChannelFully(FileChannel fileChannel, byte buf[], int off, int len)
  8. readFileChannelFully(FileChannel fileChannel, byte buf[], int off, int len)
  9. readFileDataIntoBufferBE(FileChannel fc, final int size)