Best To Read Text File In Java

In java reading text file can be done in several ways like by using Scanner, FileReader, BufferedReader, InputStreamReader classes. But for easiest and safe code one can use  FileUtils class of Apache Commons IO Java library to read text from file. If file is really large then it also provides methods to read text line by line.

Library Information

Platform information

jdk1.8.0_60, Java 8, Eclipse

Used library Name: Commons IO

Methods used: FileUtils provides 2 methods to read file text. One is with default encoding and in another we need to specify character encoding.

//Reads the contents of a file into a String.
static String    readFileToString(File file, Charset encoding)
//Reads the contents of a file into a String.
static String    readFileToString(File file, String encoding)

Example for reading file

package org.code4copy;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
public class ReadingTextFileExample {
private static void readTextFile() throws IOException {
File file1 = new File("c:\\example\\1.txt");
//Deprecated do not use this
String data = FileUtils.readFileToString(file1);
System.out.println(data);
data = FileUtils.readFileToString(file1, Charset.forName("utf-8"));
System.out.println(data);
}
public static void main(String[] args) {
try {
readTextFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output

Hello! How are you?Hello! How are you?Hello! How are you?
Hello! How are you?Hello! How are you?Hello! How are you?

Leave a Reply

Your email address will not be published. Required fields are marked *