How to read a File using BufferedReader

Here we are discussing about reading the file using BufferedReader.

To learn to read File using BufferedInputStream  Click Here.

To learn to read File using Scanner  Click Here.

package JavaIOExample;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

/*
 * Here we will learn to read the file using BufferedReader. 
 */
public class ReadTheFileUsingBufferedReader {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the File path");
		String filePath = scanner.next();

		BufferedReader br = null;

		/*
		 * Creates a new File instance by converting the given pathname string
		 * into an abstract pathname.
		 */
		File file = new File(filePath);
		String nextLine;
		try {
			/*
			 * Creates a buffering character-input stream that uses a
			 * default-sized input buffer.
			 */
			br = new BufferedReader(new FileReader(file));
			/*
			 * Reads a line of text. A line is considered to be terminated by
			 * any one of a line feed ('n'), a carriage return ('r')
			 */
			while ((nextLine = br.readLine()) != null) {
				System.out.println(nextLine);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

}

 

By | 2017-07-24T12:31:19+00:00 October 20th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment