The code snippet below is an example of how to read a text file using BufferedReader
class from the java.io
package. This snippet read a text file called README.md
and print out its content.
To create an instance of java.io.BufferedReader
we do the following steps:
File file = new File("README.md");
FileReader fileReader = new FileReader(file));
BufferedReader bufferedReader = new BufferedReader(fileReader);
Let’s see the complete code snippet.
package org.kodejava.io;
import java.io.*;
public class ReadTextFileExample {
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static void main(String[] args) {
File file = new File("README.md");
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
StringBuilder contents = new StringBuilder();
String text;
while ((text = reader.readLine()) != null) {
contents.append(text).append(LINE_SEPARATOR);
}
System.out.println(contents.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can also try to use the following example to read a file, How do I read text file content line by line using commons-io?. To create and write a text file see the following example: How do I create and write data into text file?.