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;

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

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

public class Main {
    /**//from   ww  w  .j a  v  a 2 s.  com
     * 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. readTextFile(File file)
  2. readTextFile(File file)
  3. readTextFile(File file)
  4. readTextFile(File file)
  5. readTextFile(File file)
  6. readTextFile(File file)
  7. readTextFile(File file)
  8. readTextFile(File file, boolean newline)
  9. readTextFile(File file, int header)