Java File Content to Byte Array getFileContentsAsByteArray(String filename)

Here you can find the source of getFileContentsAsByteArray(String filename)

Description

Read in the contents of a file into a byte array

License

MIT License

Parameter

Parameter Description
filename The file to read

Exception

Parameter Description
FileNotFoundException an exception
IOException an exception

Return

A byte array containing the contents of the file

Declaration

public static byte[] getFileContentsAsByteArray(String filename) throws FileNotFoundException, IOException 

Method Source Code


//package com.java2s;
/*/* ww  w  .  j  a  v  a  2s.  c  om*/
 *
 * Copyright (C) 2010 Saumitro Dasgupta.
 *
 * This code is made available under the MIT License.
 * <http://www.opensource.org/licenses/mit-license.html>
 *
 */

import java.io.*;

public class Main {
    /**
     *
     * Read in the contents of a file into a byte array
     *
     * @param filename The file to read
     * @return A byte array containing the contents of the file
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] getFileContentsAsByteArray(String filename) throws FileNotFoundException, IOException {

        File file = new File(filename);
        FileInputStream fis = new FileInputStream(file);

        int len = (int) file.length();

        byte[] bytes = new byte[len];

        int bytesRead = 0;
        int offset = 0;

        while (offset < len) {

            bytesRead = fis.read(bytes, offset, len - offset);

            if (bytesRead == -1)
                break;

            offset += bytesRead;

        }

        if (offset < len)
            throw new IOException("Unable to read in all the bytes");

        fis.close();

        return bytes;

    }
}

Related

  1. getFileContentAsByteArray(String fileName)
  2. getFileContentAsByteArray(String fileName)
  3. getFileContentAsBytes(String fileName)
  4. getFileContentAsBytes(String fileName)
  5. getFileContentByte(InputStream inputStream, long offset, int length)