Java InputStreamReader Read readFile(File path)

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

Description

Reads the entire contents of the file at the given path and returns it as a String.

License

Apache License

Parameter

Parameter Description
path path of the file to read

Exception

Parameter Description
IOException on any error

Return

the file content as a String

Declaration

public static String readFile(File path) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    private static final int BUFFER_SIZE = 8192;

    /**/*from w w  w  .  j  av  a 2s  .c  o  m*/
     * Reads the entire contents of the file at the given path and returns it as a String.  Uses the default locale.
     *
     * @param path path of the file to read
     * @return the file content as a String
     * @throws IOException on any error
     */
    public static String readFile(File path) throws IOException {
        InputStreamReader reader = null;
        try {
            StringWriter writer = new StringWriter();
            reader = new InputStreamReader(new FileInputStream(path));

            int n;
            char[] buffer = new char[BUFFER_SIZE];
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }

            reader.close();
            return writer.toString();
        } finally {
            failsafeClose(reader);
        }
    }

    /**
     * Closes a given closeable if it is not null, and ignores thrown errors.  Useful for finally
     * clauses which perform last-ditch cleanup and don't want to throw (masking earlier errors).
     *
     * @param closeable to be closed
     */
    public static void failsafeClose(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                // Ignored.
            }
        }
    }
}

Related

  1. readFile(File file, String encoding)
  2. readFile(File file, String encoding)
  3. readFile(File file, String encoding)
  4. readFile(File file, String encoding)
  5. readFile(File filename)
  6. readFile(File resultFile)
  7. readFile(File target)
  8. readFile(FileInputStream file)
  9. readFile(final File file)