Java File Content to Byte Array getFileContentAsByteArray(String fileName)

Here you can find the source of getFileContentAsByteArray(String fileName)

Description

Returns the content of a given file as byte array.

License

Open Source License

Parameter

Parameter Description
fileName Description of the Parameter

Return

The content in a String or empty String, if an error occured.

Declaration

public static byte[] getFileContentAsByteArray(String fileName) throws Exception 

Method Source Code


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

import java.io.*;

public class Main {
    /**//ww w . ja v a2  s  . c om
     * Returns the content of a given file as byte array.
     * 
     * @param fileName
     *            Description of the Parameter
     * @return The content in a String or empty String, if an error occured.
     * @exception Exception
     *                Description of the Exception
     */
    public static byte[] getFileContentAsByteArray(String fileName) throws Exception {
        RandomAccessFile raf = new RandomAccessFile(fileName, "r");
        Long lengthFile;
        byte[] b;
        try {
            raf.seek(0);
            lengthFile = new Long(raf.length());
            b = new byte[lengthFile.intValue()];
            raf.readFully(b);
        } catch (Exception e) {
            System.err.println("failed to get content from file: " + e.toString());
            // e.printStackTrace();
            throw new Exception();
        } finally {
            raf.close();
            raf = null;
            lengthFile = null;
        }
        return b;
    }
}

Related

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