Java FileReader Read readFile(String fileName)

Here you can find the source of readFile(String fileName)

Description

Reads the content of a given file.

License

Open Source License

Parameter

Parameter Description
fileName the name of the file to read.

Exception

Parameter Description
IOException if any error occurs during reading.

Return

a string represents the content.

Declaration

private static String readFile(String fileName) throws IOException 

Method Source Code


//package com.java2s;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class Main {
    /**//from  w  w w.j av a  2 s  .com
     * Reads the content of a given file.
     *
     * @param fileName the name of the file to read.
     * @return a string represents the content.
     * @throws IOException if any error occurs during reading.
     */
    private static String readFile(String fileName) throws IOException {
        Reader reader = new FileReader(fileName);

        try {
            // Create a StringBuilder instance
            StringBuilder sb = new StringBuilder();

            // Buffer for reading
            char[] buffer = new char[1024];

            // Number of read chars
            int k = 0;

            // Read characters and append to string builder
            while ((k = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, k);
            }

            // Return read content
            return sb.toString().replace("\r\n", "\n");
        } finally {
            reader.close();
        }
    }
}

Related

  1. readFile(String filename)
  2. readFile(String filename)
  3. readFile(String filename)
  4. readFile(String fileName)
  5. readFile(String fileName)
  6. readFile(String filename)
  7. readFile(String fileName)
  8. readFile(String filename)
  9. readFile(String filename)