Java FileInputStream Read readFile(File f, int iChunkSize)

Here you can find the source of readFile(File f, int iChunkSize)

Description

Converts a file into a byte array.

License

Open Source License

Parameter

Parameter Description
f a parameter
iChunkSize a parameter

Declaration

public static byte[] readFile(File f, int iChunkSize) 

Method Source Code

//package com.java2s;
/** ***************************************************************
Util.java/*from ww w .j  av  a2 s  . co m*/
Copyright (C) 2001  Brendon Upson 
http://www.wnc.net.au info@wnc.net.au
    
This program 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 2 of the License, or
(at your option) any later version.
    
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
    
 *************************************************************** */

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

public class Main {
    /**
     * Converts a file into a byte array. ChunkSize specifies the size of each read, if set to <1 defaults to 4096
     * @param f
     * @param iChunkSize
     * @return
     */
    public static byte[] readFile(File f, int iChunkSize) {
        if (iChunkSize < 1)
            iChunkSize = 4096;
        try {
            FileInputStream fin = new FileInputStream(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream(iChunkSize);
            byte buf[] = new byte[iChunkSize]; //4k chunks
            while (fin.available() > 0) {
                int iRead = fin.read(buf);
                if (iRead > 0)
                    baos.write(buf, 0, iRead);
            }
            fin.close();
            return baos.toByteArray();
        } catch (Exception e) {
        }
        return null;
    }
}

Related

  1. readFile(File f)
  2. readFile(File f)
  3. readFile(File f)
  4. readFile(File f)
  5. readFile(File f, int fetchLength, byte[] bytes)
  6. readFile(File file)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(File file)