Here you can find the source of readTextFile(java.io.File file)
Parameter | Description |
---|---|
file | Text file to read from. |
Parameter | Description |
---|---|
IOException | if file cannot be read. |
public static String readTextFile(java.io.File file) throws IOException
//package com.java2s; /* Please see the license information at the end of this file. */ import java.io.*; public class Main { /** Read text file to a string. *// w w w .j a va 2 s . c o m * @param file Text file to read from. * @param encoding Text file encoding, e.g., "utf-8". * * @return Contents of file as a string. * * @throws IOException * if file cannot be read. */ public static String readTextFile(java.io.File file, String encoding) throws IOException { StringBuffer contents = new StringBuffer((int) file.length()); BufferedReader bufferedReader; String safeEncoding = (encoding == null) ? "" : encoding; if (safeEncoding.length() > 0) { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), safeEncoding)); } else { bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); } boolean eof = false; String contentLine = ""; String eolChar = "\n"; while (!eof) { contentLine = bufferedReader.readLine(); if (contentLine == null) { eof = true; } else { contents.append(contentLine); contents.append(eolChar); } } bufferedReader.close(); return contents.toString(); } /** Read text file to a string. * * @param file Text file to read from. * * @return Contents of file as a string. * * @throws IOException * if file cannot be read. */ public static String readTextFile(java.io.File file) throws IOException { return readTextFile(file, null); } /** Read text file to a string. * * @param fileName Text file name to read from. * @param encoding Text file encoding, e.g., "utf-8". * * @return Contents of file as a string. * * @throws IOException * if file cannot be read. */ public static String readTextFile(String fileName, String encoding) throws IOException { return readTextFile(new java.io.File(fileName), encoding); } /** Read text file to a string. * * @param fileName Text file name to read from. * * @return Contents of file as a string. * * @throws IOException * if file cannot be read. */ public static String readTextFile(String fileName) throws IOException { return readTextFile(new java.io.File(fileName)); } }