Here you can find the source of fileToBytes(File source)
Parameter | Description |
---|---|
source | the file |
Parameter | Description |
---|---|
IOException | an exception |
public static byte[] fileToBytes(File source) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /**/*www . jav a 2s . c o m*/ * Reads the contents of a file as a byte[]. Obviously be careful * with memory. * * @param source the file * @return the byte[] with the bytes of the file * @throws IOException */ public static byte[] fileToBytes(File source) throws IOException { FileInputStream fIn = null; try { fIn = new FileInputStream(source); byte[] bytes = new byte[(int) source.length()]; int read = 0; while (read < bytes.length) { int thisRead = fIn.read(bytes, read, bytes.length - read); if (thisRead == -1) { throw new IOException("Premature end of stream"); } read += thisRead; } close(fIn); return bytes; } catch (IOException ex) { close(fIn); throw ex; } } /** * Safe close of an OutputStream (no exceptions, * even if reference is null). * * @param out the stream to close */ public static void close(OutputStream out) { try { out.close(); } catch (Exception ignore) { } } /** * Safe close of an InputStream (no exceptions, * even if reference is null). * * @param in the stream to close */ public static void close(InputStream in) { try { in.close(); } catch (Exception ignore) { } } }