Java BufferedReader Read readFile(File file)

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

Description

Reads the contents of a file returning it as a String.

License

Open Source License

Parameter

Parameter Description
file a parameter

Exception

Parameter Description
IOException an exception

Return

The contents of the file

Declaration

public static String readFile(File file) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2013 Nick Robinson 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
 ******************************************************************************/

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

public class Main {
    /**/*from   w w w  .  j ava 2 s  .  co  m*/
     * Reads the contents of a file returning it as a String. Only use this if you know that the file is small, beacause a large file will
     * consume all available memory, which will, at best crash the program and at worst will make the computer so unresponsive that you'll
     * need to reboot it uncleanly.
     * 
     * @param file
     * @return The contents of the file
     * @throws IOException
     */
    public static String readFile(File file) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(file));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append('\n');
                line = br.readLine();
            }
            return sb.toString();
        } finally {
            br.close();
        }
    }
}

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)