Reading Text File Example - Java.io.BufferedReader.read() Method


Introduction

Java BufferedReader class is used to read the text from a character-based input stream. It can be used to read data line by line by readLine() method. It makes the performance fast. It inherits Reader class.

The Java.io.BufferedReader class buffers characters so as to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used.

Inside the text file

line 1
line 2
line 3
line 4
line 5

Sample Code:reading the data from the text file using read()

read() method of java.io.BufferedReader class
It is used for reading a single character and it returns an integer.

import java.io.BufferedReader;
import java.io.FileReader;

public class main {
public static void main (String [] args) throws Exception {

//Read the data from the text file using Java BufferedReader class.

FileReader fileReader = new FileReader("C:\\text.txt");

//creates a buffering character-input stream that uses a default-sized input buffer
BufferedReader bufferedReader=new BufferedReader(fileReader);

int i;

//The Method read() is used for reading a single character.
while ((i=bufferedReader.read())!=-1)
{
System.out.print((char)i);
}

//closes the stream and releases any system resources associated with it
bufferedReader.close();
fileReader.close();
}
}

Output from The Program

line 1
line 2
line 3
line 4
line 5

Java BufferedReader Class

張貼留言

0 留言