Here you can find the source of readFile(String fileName)
Parameter | Description |
---|---|
fileName | the name of the file to read. |
Parameter | Description |
---|---|
IOException | if any error occurs during reading. |
private static String readFile(String fileName) throws IOException
//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(); } } }