Java FileInputStream Read readFile(File file)

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

Description

reads the file specified in to a string.

License

Open Source License

Parameter

Parameter Description
file .

Declaration

public static String readFile(File file) 

Method Source Code

//package com.java2s;
/**/* w  w w  . j  a v a2 s  .c o  m*/
 * A class of utilities related to strings. Originally written by Alexander Boyd
 * for the OpenGroove project (www.opengroove.org). Released under the terms of
 * the GNU Lesser General Public License.
 * 
 * @author Alexander Boyd
 * 
 */

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

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

public class Main {
    /**
     * reads the file specified in to a string. the file must not be larger than
     * 5 MB.
     * 
     * @param file
     *            .
     * @return
     */
    public static String readFile(File file) {
        try {
            if (file.length() > (5 * 1000 * 1000))
                throw new RuntimeException("the file is " + file.length()
                        + " bytes. that is too large. it can't be larger than 5000000 bytes.");
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            FileInputStream fis = new FileInputStream(file);
            copy(fis, baos);
            fis.close();
            baos.flush();
            baos.close();
            return new String(baos.toByteArray(), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Copies the contents of one stream to another. Bytes from the source
     * stream are read until it is empty, and written to the destination stream.
     * Neither the source nor the destination streams are flushed or closed.
     * 
     * @param in
     *            The source stream
     * @param out
     *            The destination stream
     * @throws IOException
     *             if an I/O error occurs
     */
    public static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[8192];
        int amount;
        while ((amount = in.read(buffer)) != -1) {
            out.write(buffer, 0, amount);
        }
    }
}

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, boolean compress)
  8. readFile(File file, int size)
  9. readFile(File file, OutputStream output)