Sunday, February 3, 2019

Difference between BufferedReader and Scanner:
  1. 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.
  2. 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.
  3. 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
  4. 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.
  5. 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. 
Example for BufferedReader:
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();
}
     }
}

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

selenium-repo by venu

Blog helps to a student or IT employee to develop or improve skills in Software Testing.
For Online Classes Email us: gadiparthi122@mail.com

Followers

About Me

My photo
Hyderabad, Andhra Pradesh, India
I am Automation Testing Professional. I have completed my graduation in B.Tech (Computers) from JNTU Hyderabad and started my career in Software Testing accidentally since then, I passionate on learning new technologies

Contact Form

Name

Email *

Message *

Popular Posts