Here you can find the source of getBytesFromFile(File file)
Parameter | Description |
---|---|
file | the file to read |
Parameter | Description |
---|---|
IOException | if the file cannot be read |
public static byte[] getBytesFromFile(File file) throws IOException
//package com.java2s; /******************************************************************************* * Copyright 2006 - 2012 Vienna University of Technology, * Department of Software Technology and Interactive Systems, IFS * /*w w w . j ava2s .com*/ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main { /** * Reads all bytes from the given file and returns a byte array. * * @param file * the file to read * @return the data read from the file * @throws IOException * if the file cannot be read */ public static byte[] getBytesFromFile(File file) throws IOException { if (file == null) { return null; } InputStream is = new BufferedInputStream(new FileInputStream(file)); byte[] bytes; try { // Get the size of the file long length = file.length(); if (length > Integer.MAX_VALUE) { throw new IOException("File is too large " + file.getName()); } // Create the byte array to hold the data bytes = new byte[(int) length]; // 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 file " + file.getName()); } } finally { // Close the input stream and return bytes is.close(); } return bytes; } }