Here you can find the source of getBytesFromFile(File file)
Parameter | Description |
---|---|
file | a parameter |
Parameter | Description |
---|---|
IOException | an exception |
public static byte[] getBytesFromFile(File file) throws IOException
//package com.java2s; /******************************************************************************* * Copyright (c) 2013 "Ivo van Kamp"/*from www. j a va2 s. c o m*/ * * jEncrypt is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ import java.io.*; public class Main { /** * Return the contents of a file as a byte array. * * @param file * @return * @throws IOException */ public static byte[] getBytesFromFile(File file) throws IOException { if (file.length() > Integer.MAX_VALUE) { // File is too large throw new IOException("File '" + file.getName() + "' is bigger than Integer.MAX_VALUE (>2GB)"); } InputStream in = new FileInputStream(file); // Create the byte array to hold the data byte[] bytes = new byte[(int) file.length()]; int len = 0; // Reads bytes from the input stream and store them in buffer bytes len = in.read(bytes); // Ensure all the bytes have been read in if (len != bytes.length) { in.close(); throw new IOException("Could not completely read file " + file.getName()); } // Close the input stream and return bytes in.close(); return bytes; } }