Java FileInputStream Read readFileToByteArray(String file)

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

Description

Reads a file storing intermediate data into an array.

License

Apache License

Parameter

Parameter Description
file the file to be read

Return

a file data

Declaration

public static byte[] readFileToByteArray(String file) 

Method Source Code


//package com.java2s;
/*/*from ww  w.j a  v a  2  s  .co m*/
 *Copyright 2012 The SCAPE Project Consortium.
 * 
 *Licensed under the Apache License, Version 2.0 (the "License");
 *you may not use this file except in compliance with the License.
 *You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 *Unless required by applicable law or agreed to in writing, software
 *distributed under the License is distributed on an "AS IS" BASIS,
 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *See the License for the specific language governing permissions and
 *limitations under the License.
 *under the License.
 */

import java.io.*;

public class Main {
    /**
     *Reads a file storing intermediate data into an array.
     *@param file the file to be read
     *@return a file data
     */
    public static byte[] readFileToByteArray(String file) {
        InputStream in = null;
        byte[] buf = null; // output buffer
        int bufLen = 20 * 1024 * 1024;
        try {
            in = new BufferedInputStream(new FileInputStream(file));
            buf = new byte[bufLen];
            byte[] tmp = null;
            int len = 0;
            //List data = new ArrayList(24);
            while ((len = in.read(buf, 0, bufLen)) != -1) {
                tmp = new byte[len];
                System.arraycopy(buf, 0, tmp, 0, len);
            }
            if (in != null) {
                try {
                    in.close();
                } catch (Exception _) {
                }
            }
        } catch (IOException e) {

        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception _) {
                }
            }
        }
        return buf;
    }

    /**
     * @param out The closeable (Writer, Stream, etc.) to close
     */
    public static void close(final Closeable out) {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

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