Difference between BufferedReader and Scanner:
- It can parse the user input and read an int, short, byte, float, long and double apart from String. On the other hand, BufferedReader can only read String in Java.
- BuffredReader has a significantly large buffer (8KB) than Scanner (1KB), which means if you are reading long String from a file, you should use BufferedReader but for short input and input other than String, you can use Scanner class.
- BufferedReader is older than Scanner. It's present in Java from JDK 1.1 onward but Scanner is only introduced in JDK 1.5 release
- Scanner uses regular expression to read and parse text input. It can accept custom delimiter and parse text into primitive data type. While, BufferedReader can only read and store String using readLine() method.
- Another major difference between BufferedReader and Scanner class is that BufferedReader is synchronized while Scanner is not. This means, you cannot share Scanner between multiple threads but you can share the BufferedReader object.This synchronization also makes BufferedReader little bit slower in single thread environment as compared to Scanner, but the speed difference is compensated by Scanner's use of regex, which eventually makes BufferedReader faster for reading String.
package seleniumrepo.filehandling;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {
String strCurrentLine;
try{
BufferedReader br=new BufferedReader(new FileReader ("System.getProperty("user.dir")+"\\testdata\\FileA.txt"));
while((strCurrentLine=br.readLine())!=null) {
System.out.println(strCurrentLine);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {
String strCurrentLine;
try{
BufferedReader br=new BufferedReader(new FileReader ("System.getProperty("user.dir")+"\\testdata\\FileA.txt"));
while((strCurrentLine=br.readLine())!=null) {
System.out.println(strCurrentLine);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example for Scanner:
package seleniumrepo.filehandling;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {
File file=new File(System.getProperty("user.dir")+"\\src\\test\\resources\\testdata\\FileA.txt");
Scanner sc=new Scanner(file);
while(sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close(); //closing scanner
}
}
0 comments:
Post a Comment