Java BufferedReader Read readFile(File file)

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

Description

Reads the contents of a file

License

Open Source License

Parameter

Parameter Description
file The file this function reads from.

Exception

Parameter Description
IOException If the file cannot be read or something similar

Return

The contents or null on error.

Declaration

public static String readFile(File file) throws IOException 

Method Source Code


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

import java.io.*;

public class Main {
    /**/*from  w  w w.  j a v  a 2 s  .c om*/
     * Reads the contents of a file
     *
     * @param file The file this function reads from.
     * @return The contents or null on error.
     * @throws IOException If the file cannot be read or something similar
     */
    public static String readFile(File file) throws IOException {
        if (file.exists()) {
            if (file.canRead()) {
                StringBuilder content = new StringBuilder();

                BufferedReader input = null;
                try {
                    input = new BufferedReader(new FileReader(file));
                    char[] buffer = new char[1024];
                    int n;

                    while ((n = input.read(buffer)) != -1) {
                        content.append(buffer, 0, n);
                    }
                } finally {
                    if (input != null) {
                        input.close();
                    }
                }

                return content.toString();
            } else {
                throw new IOException("File " + file.getPath() + " is not readable.");
            }
        } else {
            throw new FileNotFoundException("File " + file.getPath() + " does not exist.");
        }
    }
}

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)