Java BufferedReader Read readFile(File file)

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

Description

Read the content of a text file and then return its contents

License

Open Source License

Parameter

Parameter Description
file File to be read

Exception

Parameter Description
FileNotFoundException If the file doesn't exist, is a directory or (rarely) failed reading
IOException If an I/O error happend while reading

Return

Contents of the file

Declaration

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

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;

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

import java.io.IOException;

public class Main {
    /**/*from  w w w  .ja  v a2  s. com*/
     * Read the content of a text file and then return its contents
     * @param file File to be read
     * @return Contents of the file
     * @throws FileNotFoundException If the file doesn't exist, is a directory or (rarely) failed reading
     * @throws IOException If an I/O error happend while reading
     */
    public static String readFile(File file) throws FileNotFoundException, IOException {
        BufferedReader bis = null;
        StringBuilder sb = new StringBuilder();
        try {
            bis = new BufferedReader(new FileReader(file));

            String line;
            while ((line = bis.readLine()) != null)
                sb.append(line).append('\n');
        } catch (FileNotFoundException e) {
            if (bis != null)
                bis.close();
            throw e;
        } finally {
            bis.close();
        }
        return sb.toString();
    }
}

Related

  1. readFile(File file)
  2. readFile(File file)
  3. readFile(File file)
  4. readFile(File file)
  5. readFile(File file)
  6. readFile(File file)
  7. readFile(File file)
  8. readFile(File file)
  9. readFile(File file)