Java FileInputStream Read readFile(File file, String encoding)

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

Description

read File

License

Open Source License

Declaration

public static String readFile(File file, String encoding)
            throws IOException 

Method Source Code

//package com.java2s;
/*//from ww w .j a  va 2 s .  c  o m
 * DiTAA - Diagrams Through Ascii Art
 * 
 * Copyright (C) 2004 Efstathios Sideris
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *   
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    public static String readFile(File file) throws IOException {
        return readFile(file, null);
    }

    public static String readFile(File file, String encoding)
            throws IOException {
        InputStream is = new FileInputStream(file);
        long length = file.length();

        if (length > Integer.MAX_VALUE) {
            // File is too large
            // TODO: we need some feedback for the case of the file being too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "
                    + file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        if (encoding == null) {
            return new String(bytes);
        } else {
            return new String(bytes, encoding);
        }
    }
}

Related

  1. readFile(File file)
  2. readFile(File file, boolean compress)
  3. readFile(File file, int size)
  4. readFile(File file, OutputStream output)
  5. readFile(File file, String encoding)
  6. readFile(File file, String encoding)
  7. readFile(File fyl)
  8. readFile(File path)
  9. readfile(File path)