Here you can find the source of getFileContentsAsByteArray(String filename)
Parameter | Description |
---|---|
filename | The file to read |
Parameter | Description |
---|---|
FileNotFoundException | an exception |
IOException | an exception |
public static byte[] getFileContentsAsByteArray(String filename) throws FileNotFoundException, IOException
//package com.java2s; /*/* ww w . j a v a 2s. c om*/ * * Copyright (C) 2010 Saumitro Dasgupta. * * This code is made available under the MIT License. * <http://www.opensource.org/licenses/mit-license.html> * */ import java.io.*; public class Main { /** * * Read in the contents of a file into a byte array * * @param filename The file to read * @return A byte array containing the contents of the file * @throws FileNotFoundException * @throws IOException */ public static byte[] getFileContentsAsByteArray(String filename) throws FileNotFoundException, IOException { File file = new File(filename); FileInputStream fis = new FileInputStream(file); int len = (int) file.length(); byte[] bytes = new byte[len]; int bytesRead = 0; int offset = 0; while (offset < len) { bytesRead = fis.read(bytes, offset, len - offset); if (bytesRead == -1) break; offset += bytesRead; } if (offset < len) throw new IOException("Unable to read in all the bytes"); fis.close(); return bytes; } }