Enter your email id to get regular update free
Your Email

What are the different ways of Reading a text file in Java?

There are multiple ways of writing and reading a text file. It is required while dealing with many applications.

Some of the ways of reading the files are:
1.Using BufferedReader:
This method reads text from a character-input stream. It bufferis for efficient reading of characters, arrays, and lines.The buffer size may be specified or the default size may be used. 
The default is large enough for most purposes.
To wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.
import java.io.*;
public class ReadFromFile2
 public static void main(String[] args)throws Exception
 File file = new File("C:\\Users\\My\\Desktop\\test.txt"); BufferedReader br = new BufferedReader(new FileReader(file)); String st; while ((st = br.readLine()) != null)
2.Using FileReader class: 
The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate.
import java.io.*;
public class ReadingFromFile
 public static void main(String[] args)
throws Exception
FileReader fr=new FileReader 
 int i;
 while ((i=fr.read()) != -1)
 System.out.print((char) i);
3.Using Scanner class:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. 
The resulting tokens may then be converted into values of different types using the various next methods.
import java.io.File;
 import java.util.Scanner;
public class ReadFromFileUsingScanner
 public static void main(String[] args) throws Exception
File file = new File("C:\\Users\\My\\Desktop\\test.txt");
 Scanner sc = new Scanner(file);
 while (sc.hasNextLine())
4. Reading the whole file in a List: 
It read all lines from a file. This method ensures that the file is closed when all bytes have been read  or other runtime exception is thrown.
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
 import java.io.*;
 public class ReadFileIntoList
 public static List
5.Reading a text file as String in Java:
To read a text file as string use the below code.
import java.nio.file.*;
public class ReadTextAsString
{ public static String readFileAsString(String fileName)throws Exception
 return data;
 public static void main(String[] args)
throws Exception {
Stringdata=readFileAsString("C:\\Users\\My\\Desktop\\test.java"); System.out.println(data);
Run these codes on IDE to check the output.
Reading a text
Different ways of Reading
Tech writer at newsandstory
Total 78 views