Here you can find the source of readFileToByteArray(String filename)
Parameter | Description |
---|---|
fileName | a parameter |
public static byte[] readFileToByteArray(String filename) throws IOException
//package com.java2s; /*/*from w ww.ja v a2 s. c om*/ * This file is part of smarthomatic, http://www.smarthomatic.org. * Copyright (c) 2013 Uwe Freese * * smarthomatic 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. * * smarthomatic 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 smarthomatic. If not, see <http://www.gnu.org/licenses/>. */ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class Main { /** * Read a text file and return the content as array of bytes. * from http://stackoverflow.com/questions/858980/file-to-byte-in-java * @param fileName * @return */ public static byte[] readFileToByteArray(String filename) throws IOException { File file = new File(filename); ByteArrayOutputStream ous = null; InputStream ios = null; try { byte[] buffer = new byte[4096]; ous = new ByteArrayOutputStream(); ios = new FileInputStream(file); int read = 0; while ((read = ios.read(buffer)) != -1) { ous.write(buffer, 0, read); } } finally { try { if (ous != null) ous.close(); } catch (IOException e) { } try { if (ios != null) ios.close(); } catch (IOException e) { } } return ous.toByteArray(); } }