There are many times during our project work we need to read a text file in java. There are many ways to read a text file in java. One can use FileReader, BufferedReader and Scanner to read a text file.
Java 8 introduced Stream class java.util.stream.Stream which gives a lazy and more efficient way to read a file line by line.
BufferedReader uses buffering of data for very fast reading.
Reading a text file using BufferedReader
BufferedReader is very simple and high performance technique of reading text files in Java. It reads the text from a character input stream. It does the buffering of characters, arrays and lines for efficient reading.
The buffer size can be specified or the default size can be used.
package ReadFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class BufferedReaderExample
{
public static void main(String[] args)throws Exception
{
//place where file is located. double backward slash should be used.
File file = new File("C:\\Users\\Desktop\\test.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String string;
while ((string = br.readLine()) != null)
System.out.println(string);
}
}
Using try with resource and nio
package ReadFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class BufferedReaderExample {
public static void main(String[] args) throws Exception {
//using class of nio file package
Path filePath = Paths.get("C:\\Users\\Desktop\\test.txt");
//converting to UTF 8
Charset charset = StandardCharsets.UTF_8;
//try with resource
try (BufferedReader bufferedReader = Files.newBufferedReader(filePath, charset)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
System.out.format("I/O exception: ", ex);
}
}
}
Reading a text file using FileReader
FileReader
is used for reading streams of characters. For reading streams of raw bytes, try using a FileInputStream
.
Clik here to view.

package ReadFile;
import java.io.FileReader;
public class FileReaderExample {
public static void main(String[] args) throws Exception {
FileReader fileReader = new FileReader("C:\\Users\\Desktop\\test.txt");
int i;
while ((i = fileReader.read()) != -1)
System.out.print((char) i);
}
}
Reading a text file using Scanner
package ReadFile;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
public class ScannerReaderExample {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\pankaj\\Desktop\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}
Java read file line by line using Files.readAllLines()
Files.readAllLines() is a method of the Java NIO Files class which reads all the lines of a file and then returns a List<String>
containing each line. Internally it uses BufferedReader to read the file.
package ReadFile;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class ReaderExample {
public static void main(String[] args) throws Exception {
Path filePath = Paths.get("c://test.txt");
Charset charset = StandardCharsets.UTF_8;
try {
List<String> lines = Files.readAllLines(filePath, charset);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException ex) {
System.out.format("I/O Exception", ex);
}
}
}
Java read file line by line using Files.lines()
Files.lines() method reads all the lines from the file as Stream
. Stream API methods can be used like forEach
, map
to get record with each line of the file.
package ReadFile;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReaderExample {
public static void main(String[] args) throws Exception {
Path filePath = Paths.get("c://demo.txt");
Charset charset = StandardCharsets.UTF_8;
try {
//converting to stream
Files.lines(filePath, charset).forEach(System.out::println);
} catch (IOException ex) {
System.out.format("I/O Exception:", ex);
}
}
}
Java read file into byte using Files.readAllBytes()
It reads all bytes from a file.
This method ensures that file is closed when all bytes had been read or an I/O error, or other runtime exception, is thrown.
This method should be used for simple needs where it is easy to read all bytes into a byte array. It should not be used for reading in large files.
It throws
IOException
– if an I/O error occurs while reading from the stream
OutOfMemoryError
– If file size is more than 2 GB then this error will be thrown.
SecurityException
–checkRead
method will be invoked to check read access to the file.
package ReadFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ReaderExample {
public static void main(String[] args) throws Exception {try {
byte[] data = Files.readAllBytes(Paths.get("C:\\Users\\Desktop\\test.txt"));
// Use byte data
System.out.println(new String(data));
} catch (IOException ex) {
System.out.format("I/O Exception ", ex);
}}
}
Conclusion
That’s all readers. You have learned how to read a text file in java.
How to Write to File Line by Line in Java with Examples
The post How to Read a text file in Java appeared first on TechBlogStation.