Java FileReader Read All readAll(File file)

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

Description

read the contents of a file into a String

License

Open Source License

Parameter

Parameter Description
file The file has to exist

Exception

Parameter Description
IOException an exception

Return

The contents of the file as String

Declaration

public static String readAll(File file) throws IOException 

Method Source Code

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

import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**/*  www  .  jav a  2  s . c o m*/
     * read the contents of a file into a String
     * 
     * @param file
     *            The file has to exist
     * @return The contents of the file as String
     * @throws IOException
     */
    public static String readAll(File file) throws IOException {
        FileReader fileReader = new FileReader(file);
        try {
            StringBuffer sb = new StringBuffer();
            char[] b = new char[8192];
            int n;
            while ((n = fileReader.read(b)) > 0) {
                sb.append(b, 0, n);
            }
            return sb.toString();
        } finally {
            fileReader.close();
        }
    }

    /**
     * read the contents of a stream into a String
     * <p>
     * ATTN: does not handle encodings
     * 
     * @param inputStream
     *            The input stream
     * @return A String representation of the file contents
     * @throws IOException
     */
    public static String readAll(InputStream inputStream)
            throws IOException {
        try {
            StringBuffer sb = new StringBuffer();
            byte[] b = new byte[8192];
            int n;
            while ((n = inputStream.read(b)) > 0) {
                sb.append(new String(b, 0, n));
            }
            return sb.toString();
        } finally {
            inputStream.close();
        }
    }
}

Related

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