Here you can find the source of readFile(String fileName)
Parameter | Description |
---|---|
fileName | the file to load. |
Parameter | Description |
---|---|
IOException | an exception |
public static byte[] readFile(String fileName) throws IOException
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main { /**/* www.j a v a 2 s.c o m*/ * Reads a file and return its content as a byte array. * @param file the file to load. * @return the byte array of its content. * */ public static byte[] readFile(File file) { byte[] bytes = null; ByteArrayOutputStream buffer = null; InputStream inputStream = null; try { inputStream = new FileInputStream(file); buffer = new ByteArrayOutputStream(); byte[] dataRead = new byte[16384]; int nbBytesRead; while ((nbBytesRead = inputStream.read(dataRead)) != -1) { buffer.write(dataRead, 0, nbBytesRead); } buffer.flush(); bytes = buffer.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { if (buffer != null) { try { buffer.close(); } catch (IOException e) { ; } } if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { ; } } } return bytes; } /** * Reads a file and return its content as a byte array. * @param fileName the file to load. * @return the byte array of its content. * @throws IOException */ public static byte[] readFile(String fileName) throws IOException { return readFile(new File(fileName)); } }