Java FileReader Read All readAll(String path)

Here you can find the source of readAll(String path)

Description

Overloaded.

License

Open Source License

Parameter

Parameter Description
path A path to the file to be read.

Return

String object on success, null otherwise.

Declaration

public static String readAll(String path) 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileReader;

public class Main {
    private static final int _BUFFER_SIZE = 1024;

    /**/*from   w  ww  . j av a2 s.c  om*/
     * Reads all of content in given file.
     * 
     * @param file File object representing the file to be read.
     * @return String object on success, null otherwise.
     */
    public static String readAll(File file) {
        StringBuilder content = new StringBuilder();
        FileReader fileReader = null;

        try {
            fileReader = new FileReader(file);

            char[] buffer = new char[_BUFFER_SIZE];
            int charactersRead = 0;
            while ((charactersRead = fileReader.read(buffer, 0, buffer.length)) != -1) {
                content.append(buffer, 0, charactersRead);
            }
        } catch (Exception exception) {
            content.delete(0, content.length());
            content = null;
        } finally {
            try {
                if (fileReader != null) {
                    fileReader.close();
                }
            } catch (Exception exception) {
            }
        }

        return (content == null) ? null : content.toString();
    }

    /**
     * Overloaded.
     * 
     * @param path A path to the file to be read.
     * @return String object on success, null otherwise.
     * @see #readAll(File)
     */
    public static String readAll(String path) {
        return readAll(new File(path));
    }
}

Related

  1. readAll(File file)
  2. readAllKeys(String propertyFileName, String xmlFileName)
  3. readAllLines(String filePath)