Java FileReader Read readFileOrThrow(File file)

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

Description

Reads the contents of a File.

License

Apache License

Parameter

Parameter Description
file a parameter

Exception

Parameter Description
IOException an exception

Return

the content of file or null in case of an error

Declaration

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

Method Source Code

//package com.java2s;
/**// w  ww .  j a  va  2s  . c  o  m
 *
 * Copyright the original author or authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

import java.io.IOException;

import java.io.Reader;

public class Main {
    /**
     * Reads the contents of a File.
     *
     * @param file
     * @return the content of file or null in case of an error
     * @throws IOException 
     */
    public static String readFileOrThrow(File file)
            throws FileNotFoundException, IOException {
        Reader reader = null;
        try {
            reader = new FileReader(file);
            char[] buf = new char[8192];
            int len;
            StringBuilder s = new StringBuilder();
            while ((len = reader.read(buf)) >= 0) {
                s.append(buf, 0, len);
            }
            return s.toString();
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
    }
}

Related

  1. readFile(String filename)
  2. readFile(String filename)
  3. readFile(String fileName)
  4. readFile(String fileName, StringBuffer buffer)
  5. readFileAsArray(String filename)