Java BufferedReader Read readFile(File file)

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

Description

This method read a whole file and return the content.

License

Open Source License

Exception

Parameter Description
IOException when an error occurs while reading the file.

Declaration

public static String readFile(File file) throws IOException 

Method Source Code


//package com.java2s;
/*//from ww  w  .  j av  a 2 s. c  om
 * SemReview - A tool to perform semi-automatically systematic reviews using Linked Data. 
 * 
 * Authors: 
 *     Luca Ardito
 *     Giuseppe Rizzo
 *     Federico Tomassetti
 *     Antonio Vetro'
 *
 * 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 3 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, see <http://www.gnu.org/licenses/>.
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import java.io.IOException;

public class Main {
    public static final String END_LINE = "\n";

    /**
     * This method read a whole file and return the content.
     * 
     * @throws IOException
     *             when an error occurs while reading the file.
     */
    public static String readFile(File file) throws IOException {
        if (!file.exists()) {
            throw new IllegalArgumentException("Illegal path: unexisting");
        }
        if (!file.isFile()) {
            throw new IllegalArgumentException("Illegal path: not a dfile");
        }
        FileReader fr = null;
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            fr = new FileReader(file);
            reader = new BufferedReader(fr);

            String line = null;
            do {
                line = reader.readLine();
                if (line != null) {
                    buffer.append(line);
                    buffer.append(END_LINE);
                }
            } while (line != null);

        } finally {
            reader.close();
            fr.close();
        }
        return buffer.toString();
    }
}

Related

  1. readFile(File f)
  2. ReadFile(File f, boolean keep_newline)
  3. readFile(File f, boolean preserveLineBreaks)
  4. readFile(File f, String newLineChar)
  5. readFile(File file)
  6. readFile(File file)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(File file)