Here you can find the source of readTextFile(java.io.File file, String encoding)
Parameter | Description |
---|---|
file | Text file to read from. |
encoding | Text file encoding, e.g., "utf-8". |
Parameter | Description |
---|---|
IOException | if file cannot be read. |
public static String readTextFile(java.io.File file, String encoding) 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. */*from w ww .j ava 2s . 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)); } }