Java FileInputStream Read load(File file)

Here you can find the source of load(File file)

Description

load

License

Apache License

Declaration

public static byte[] load(File file) 

Method Source Code


//package com.java2s;
/*/*from   ww w. j a va 2 s .  c o  m*/
 * Copyright 2010-2012 VMware and contributors
 *
 * 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.
 */

import java.io.BufferedInputStream;

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

import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static byte[] load(File file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            byte[] data = loadBytesFromStream(fis);
            fis.close();
            return data;
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return null;
        }
    }

    /**
     * Load all the byte data from an input stream.
     * 
     * @param stream thr input stream from which to read
     * @return a byte array containing all the data from the stream
     */
    public static byte[] loadBytesFromStream(InputStream stream) {
        try {
            BufferedInputStream bis = new BufferedInputStream(stream);
            byte[] theData = new byte[10000000];
            int dataReadSoFar = 0;
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = bis.read(buffer)) != -1) {
                System.arraycopy(buffer, 0, theData, dataReadSoFar, read);
                dataReadSoFar += read;
            }
            bis.close();
            // Resize to actual data read
            byte[] returnData = new byte[dataReadSoFar];
            System.arraycopy(theData, 0, returnData, 0, dataReadSoFar);
            return returnData;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. load(File file)
  2. load(File file)
  3. load(String file)
  4. loadContents(File file)