Java File to Byte Array fileToByteArray(String fname)

Here you can find the source of fileToByteArray(String fname)

Description

file To Byte Array

License

MIT License

Declaration

public static byte[] fileToByteArray(String fname) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *  Copyright ? 2012-2015 eBay Software Foundation
 *  This program is dual licensed under the MIT and Apache 2.0 licenses.
 *  Please see LICENSE for more information.
 *******************************************************************************/

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;

public class Main {
    public static byte[] fileToByteArray(String fname) {
        File file = new File(fname);
        FileInputStream fis = null;

        try {/*from  w  w w.ja  v a2  s.  c  o  m*/
            fis = new FileInputStream(fname);
        } catch (FileNotFoundException e) {

            return null;
        }

        byte[] fileContents = new byte[(int) file.length()];

        int i = 0;

        while (true) {
            int data;
            try {
                data = fis.read();
            } catch (IOException e) {

                return null;
            } finally {
                if (fis != null)
                    try {
                        fis.close();
                    } catch (IOException e) {
                        //ignore
                    }
            }

            if (data == -1)
                break;

            fileContents[i] = (byte) data;
        }
        return fileContents;
    }
}

Related

  1. fileToByteArray(File file)
  2. fileToByteArray(File file)
  3. fileToByteArray(final File f)
  4. fileToByteArray(final IFile file)
  5. fileToByteArray(String filePath)
  6. fileToByteArray(String path)
  7. fileToBytes(File file)
  8. fileToBytes(File file)
  9. fileToBytes(File path)