Java FileReader Create readTextFile(File file)

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

Description

Read a text file and return it as a String.

License

Open Source License

Parameter

Parameter Description
file File to read

Exception

Parameter Description
FileNotFoundException If file not found or invalid path
IOException if there was an error reading the file

Return

the content of the file

Declaration

public static String readTextFile(File file) throws FileNotFoundException, IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2012 Stefan Profanter. All rights reserved. This program and the accompanying
 * materials are made available under the terms of the GNU Public License v3.0 which accompanies
 * this distribution, and is available at http://www.gnu.org/licenses/gpl.html
 * /*from   w  w w. j a  v a  2 s .  c  o m*/
 * Contributors: Stefan Profanter - initial API and implementation, Year: 2012
 ******************************************************************************/

import java.io.File;
import java.io.FileNotFoundException;

import java.io.FileReader;
import java.io.IOException;

public class Main {
    /**
     * Read a text file and return it as a String.
     * 
     * @param file
     *            File to read
     * @return the content of the file
     * @throws FileNotFoundException
     *             If file not found or invalid path
     * @throws IOException
     *             if there was an error reading the file
     */
    public static String readTextFile(File file) throws FileNotFoundException, IOException {
        FileReader fr = new FileReader(file);
        char[] cbuf = new char[(int) file.length()];
        fr.read(cbuf);
        String content = new String(cbuf);
        fr.close();
        return content;
    }

    /**
     * Read a text file and return it as a String.
     * 
     * @param filename
     *            Filename as String. File must exist otherwise a FileNotFound exception will be
     *            thrown.
     * @return the content of the file
     * @throws FileNotFoundException
     *             If file not found or invalid path
     * @throws IOException
     *             if there was an error reading the file
     */
    public static String readTextFile(String filename) throws FileNotFoundException, IOException {
        return readTextFile(new File(filename));
    }
}

Related

  1. getReader(final File file)
  2. readTextFile(File aFile)
  3. readTextFile(File f)
  4. readTextFile(File f)
  5. readTextFile(File file)
  6. readTextFile(File file)
  7. readTextFile(File file)
  8. readTextFile(File file)
  9. readTextFile(File file)