Java FileInputStream Read readFile(File file)

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

Description

read File

License

Open Source License

Declaration

public static byte[] readFile(File file) throws IOException 

Method Source Code

//package com.java2s;
/*//from w  ww.  j  ava 2  s  .  com
Milyn - Copyright (C) 2006
    
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (version 2.1) as published by the Free Software
Foundation.
    
This library 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 Lesser General Public License for more details:
http://www.gnu.org/licenses/lgpl.txt
 */

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

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

import java.io.Reader;

public class Main {
    public static byte[] readFile(File file) throws IOException {

        InputStream stream = new FileInputStream(file);
        try {
            return readStream(stream);
        } finally {
            stream.close();
        }
    }

    /**
     * Read the supplied InputStream and return as a byte array.
     *
     * @param stream
     *            The stream to read.
     * @return byte array containing the Stream data.
     * @throws IOException
     *             Exception reading from the stream.
     */
    public static byte[] readStream(InputStream stream) throws IOException {

        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        byte[] byteBuf = new byte[1024];
        int readCount = 0;

        while ((readCount = stream.read(byteBuf)) != -1) {
            bytesOut.write(byteBuf, 0, readCount);
        }

        return bytesOut.toByteArray();
    }

    public static String readStream(Reader stream) throws IOException {

        StringBuilder streamString = new StringBuilder();
        char[] readBuffer = new char[256];
        int readCount = 0;

        while ((readCount = stream.read(readBuffer)) != -1) {
            streamString.append(readBuffer, 0, readCount);
        }

        return streamString.toString();
    }
}

Related

  1. readFile(File file)
  2. readFile(File file)
  3. readFile(File file)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(File file)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(File file)