Java File to Byte Array getBytesFromFile(File file)

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

Description

Returns the contents of the file in a byte array.

License

Open Source License

Declaration

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

Method Source Code


//package com.java2s;
/*/* ww  w  .j  ava 2 s .  c  o m*/
 * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     Nuxeo - initial API and implementation
 *
 * $Id: JOOoConvertPluginImpl.java 18651 2007-05-13 20:28:53Z sfermigier $
 */

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

public class Main {
    /**
     * Returns the contents of the file in a byte array.
     */
    public static byte[] getBytesFromFile(File file) throws IOException {

        FileInputStream is = new FileInputStream(file);

        long length = file.length();
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];
        try {
            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }

            // Ensure all the bytes have been read in
            if (offset < bytes.length) {
                throw new IOException("Could not completely read InputStream");
            }
        } finally {
            // Close the input stream and return bytes
            is.close();
        }
        return bytes;
    }
}

Related

  1. getBytesFromFile(File file)
  2. getBytesFromFile(File file)
  3. getBytesFromFile(File file)
  4. getBytesFromFile(File file)
  5. getBytesFromFile(File file)
  6. getBytesFromFile(File file)
  7. getBytesFromFile(File file)
  8. getBytesFromFile(File file)
  9. getBytesFromFile(File file)