How to create an ArrayList from a File using BufferedReader?

How to create an ArrayList from a File using BufferedReader?

We will understand BufferedReader with help of this example.

Hi all, in this article we will see how to get data from a file and make an ArrayList using BufferedReader.

BufferedReader

BufferedReader is used to read data from an input stream, this stream can be anything like files, sockets, or entering data from the keyboard.
Buffer keeps chunks of data in its buffer while Reader reads data from buffer instead of the source, this reduces I/O operations.

For this example, we have created a file data.txt having players names (great batters of our Indian Cricket)

Sachin
Sehwag
Virat
Yuvraj
Raina
Dhoni

We need to make ArrayList of String with these data.
So, BufferedReader excepts a Reader in its constructor and size of the buffer which is optional.
The default size of the buffer is 8KB.
Since we are reading data from a file, we will provide FileReader.

BufferedReader br = new BufferedReader(new FileReader("src/resources/data.txt"));

Then using the readLine() method of BufferedReader class, we will read each line and then add it into the ArrayList.

BufferedReader br = new BufferedReader(new FileReader("src/resources/data.txt"));
ArrayList<String> players = new ArrayList<>();
String line = br.readLine(); //reading 1st line
while (line!=null){ //repeat until all the lines are done
     players.add(line);
     line= br.readLine(); // reading line for next iteration
}
System.out.println(players);

image.png

I hope this is clear.

If we don't want to make use of Buffer then we can do the same thing using FileReader as well, but BufferedReader has some amazing helper methods such as:-
String readLine() - reads data line by line
int read() - reads single character
boolean ready() - to check whether the input stream is ready to be read or not.

Similarly, there are many such methods you can have a look at the official documentation

This is it for the article.
I have started sharing short Java articles.
If you have any feedback for these short articles or any suggestions, do comment.
If this was helpful please give it a like.
Thanks for Reading... Bye!