Java FileInputStream Read readFile(String filename)

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

Description

Read a file into a buffer sized the size of the file

License

Apache License

Parameter

Parameter Description
filename The file full-path

Return

The file contents

Declaration

public static byte[] readFile(String filename) throws FileNotFoundException, IOException 

Method Source Code

//package com.java2s;
/**//from ww  w  . j  av  a2 s  .co m
 * Copyright (C) 2012 Red Hat, Inc. and/or its affiliates.
 *
 * 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.*;

public class Main {
    /**
     * Read a file into a buffer sized the size of the file
     *
     * @param filename The file full-path
     * @return The file contents
     */
    public static byte[] readFile(String filename) throws FileNotFoundException, IOException {
        File file = new File(filename);
        FileInputStream stream = new FileInputStream(file);

        return readFromInputStream(stream);
    }

    /**
     * Reads a set of bytes from an InputStream and returns the data as a byte
     * array.
     *
     * @param is InputStream
     * @return Array of bytes
     */
    public static byte[] readFromInputStream(InputStream is) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int copyBufferSize = 2048;

        try {
            // Transpaso de informacion
            byte[] byteData = new byte[copyBufferSize];
            int readSize;

            while ((readSize = is.read(byteData)) != -1)
                out.write(byteData, 0, readSize);
        } finally {
            // Cierro los ficheros
            is.close();
            out.close();
        }

        return out.toByteArray();
    }
}

Related

  1. readFile(String fileName)
  2. readFile(String fileName)
  3. readFile(String filename)
  4. readFile(String filename)
  5. readFile(String fileName)
  6. readfile(String filename)
  7. readFile(String filename)
  8. readFile(String fileName)
  9. readFile(String fileName)