Java File to Byte Array fileToByteArray(File file)

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

Description

Converts a file into an array of bytes.

License

Open Source License

Parameter

Parameter Description
file The file to convert.

Exception

Parameter Description
IOException an exception

Return

The file in bytes.

Declaration

public static byte[] fileToByteArray(File file) throws IOException 

Method Source Code


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

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Main {
    /**//from  ww w  .j a v  a 2s  .  c  o  m
     * Converts a file into an array of bytes.
     * 
     * @param file The file to convert.
     * 
     * @return The file in bytes.
     * 
     * @throws IOException
     */
    public static byte[] fileToByteArray(File file) throws IOException {
        final byte[] data = new byte[Math.toIntExact(file.length())];

        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(data);
        }

        return data;
    }
}

Related

  1. fileToByteArray(File file)
  2. fileToByteArray(File file)
  3. fileToByteArray(File file)
  4. FiletoByteArray(File file)
  5. fileToByteArray(final File f)
  6. fileToByteArray(final IFile file)