Java FileInputStream Read readFileToByteArray(String filename)

Here you can find the source of readFileToByteArray(String filename)

Description

Read a text file and return the content as array of bytes.

License

Open Source License

Parameter

Parameter Description
fileName a parameter

Declaration

public static byte[] readFileToByteArray(String filename)
        throws IOException 

Method Source Code

//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();
    }
}

Related

  1. readFileToBinary(File lessCSS)
  2. readFileToByteArray(File file)
  3. readFileToByteArray(File file)
  4. readFileToByteArray(File file)
  5. readFileToByteArray(String file)
  6. readFileToBytes(File f)
  7. readFileToBytes(File f, int max)
  8. readFileToBytes(String path)
  9. readFileToStr(String fn, String charset)