Java FileReader Read readFile(String fileName)

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

Description

Reads file to a string.

License

Open Source License

Parameter

Parameter Description
fileName the name of the file to read.

Exception

Parameter Description
IOException if any IO error occurs.

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 a  v  a 2  s . c o  m
     * Reads file to a string.
     * 
     * @param fileName
     *            the name of the file to read.
     * 
     * @return a string represents the content.
     * 
     * @throws IOException
     *             if any IO error occurs.
     */
    private static String readFile(String fileName) throws IOException {
        Reader reader = new FileReader(fileName);

        try {
            StringBuilder sb = new StringBuilder();
            char[] buffer = new char[1024];
            int k = 0;
            while ((k = reader.read(buffer)) != -1) {
                sb.append(buffer, 0, k);
            }
            return sb.toString().replace("\r\n", "\n");
        } finally {
            try {
                reader.close();
            } catch (IOException ioe) {
                // Ignore
            }
        }
    }
}

Related

  1. readFile(String file)
  2. readFile(String file)
  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)