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.
Do you have similar website/ Product?
Show in this page just for only
$2 (for a month)
0/60
0/180
Some of the ways of reading the files are:
2.Using FileReader class:
Run these codes on IDE to check the output.
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.
E.g:
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) System.out.println(st); } } |
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 ("C:\\Users\\My\\Desktop\\test.txt"); 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()) System.out.println(sc.nextLine()); } } |
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 {Stringdata="";data=newString(Files.readAllBytes(Paths.get(fileName))); return data; } public static void main(String[] args) throws Exception { Stringdata=readFileAsString("C:\\Users\\My\\Desktop\\test.java"); System.out.println(data); } } |
CONTINUE READING
Different ways of Reading
Ayesha
Tech writer at newsandstory