6️⃣

14.6 BufferedReader

 

BufferedReader Class

When you used InputStream and OutputStream to perform file i/o operations, you were working with bytes. The java.io.BufferedReader class is used to read text from a character input stream, instead of a byte stream. It has methods like readLine() that make it easier to parse Strings.
 
Just like java.util.Scanner, BufferedReader can read input from the console, but more importantly, it can read input from a File:
public class ReadFileDemo { public static void main(String[] args) { BufferedReader br = null; BufferedReader br2 = null; try { br = new BufferedReader(new FileReader("B:\\myfile.txt")); //One way of reading the file System.out.println("Reading the file using readLine() method:"); String contentLine = br.readLine(); while (contentLine != null) { System.out.println(contentLine); contentLine = br.readLine(); } br2 = new BufferedReader(new FileReader("B:\\myfile2.txt")); //Second way of reading the file System.out.println("Reading the file using read() method:"); int num = 0; char ch; while ((num = br2.read()) != -1) { ch = (char) num; System.out.print(ch); } } catch (IOException ioe) { ioe.printStackTrace(); } } }
 
 
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.