Java Examples- BufferedReader and BufferedWriter

Updated on April 6, 2018
sirama profile image

I am a software engineer. I have been working with C++, MFC, and .net technologies for 15 years. I like playing video games & reading books.

1. About BufferedWriter and BufferedReader

A buffer is a collective memory. Reader and Writer classes in java supports "Text Streaming". The "BufferedWriter" class of java supports writing a chain of characters output stream (Text based) in an efficient way. The Chain-Of-Characters can be Arrays, Strings etc. The "BufferedReader" class is used to read stream of text from a character based input stream.

The BufferedReader and BufferedWriter class provides support for writing and reading newline character. In windows ā€˜\r\nā€™ together forms the new line (Carriage return and Line Feed). But in Unix ā€˜\nā€™ is sufficient for a new line. With these "Buffered Text Stream" classes, we no need to worry about the platform while dealing with the Newline character.

The BufferedReader and Writer can be attached with other Reader and Writer classes for efficient streaming of the Data. In this example, we are going to overlap the FileWriter with BufferedWriter to perform the file writing. The same way, we are going to overlap BufferedReader over the FileReader. So, the net effect will be reading and writing a file with the newline character support without worrying about the underlying platform.

2. Write to a File using Java's BufferedWriter

The file reading and writing operation is error prone as it involves disc file. Say for example, there is no space in disc or the folder do not have permission to create files or the file does not exits etc. So first we need "IOException". First, we are going to write some text content to a file and to perform this we need FileWriter and BufferedWriter classes. The same-way for reading the file content, we need FileReader and BufferedReader classes. Below is the required package imports:

//Sample 01: Package inclusion
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;

Now, look at the code below which writes some string contents to a Text file:

BufferedWriter - Java Example Code Snippet
BufferedWriter - Java Example Code Snippet | Source

A FileWriter object fw is created and we are passing the file name with the path to its constructor (Marked as 1). Once we have the FileWriter object in hand, we are overlapping it with BufferedWriter. The BufferedWriter object WriteFileBuffer is created by passing the FileWriter object to its constructor (Marked as 2). We call overlapping one stream over another stream as "Stream Chaining".

The FileWriter object itself sufficient to write a text file. But, here we are overlapping it with a BufferedWriter to provide additional functionality of supporting the New Line characters. Also, the BufferedWriter minimizes the file-hit as it flushes the buffered content. Note that the text contents are written to the file TestFile.txt by calling the "write()" method (Marked as 3) . We are writing three lines of text and the "newline()" method is used to place platform specific new line character in the text file (Marked as 4). Finally, we are closing the Buffered Writer by calling the "close()" method (Marked as 5). Since the FileWriter is overlapped by the BufferedWriter, we no need to call the close() method on the FileWriter. Have a look at the below depiction:

Stream Chaining - BufferedWriter over FileWriter
Stream Chaining - BufferedWriter over FileWriter | Source

Here, when we write our content to the buffered reader (Using write() and newLine() method), the reader makes use of the FileWriter to push text stream to a text file. The FileWriter knows writing the character to a text file. The BufferedWriter knows how to write it efficiently (by buffering the characters) and it takes care writing the new line character. Note that we make use of BufferedWriter to write the text content and BufferedWriter uses its underlying FileWriter.

3. Read from a File using Java's BufferedReader

In the previous section, we created a file using BufferedWriter. Now, we will read that TestFile.txt file and display the content of it in the console output window. To read the text file, we are going to use BufferedReader. Have a look at the code snippet below:

Reading Text file content using Java's BufferedReader
Reading Text file content using Java's BufferedReader | Source

First, the java FileReader object fr is created. We are passing full path to the text file in the constructor (Marked as 1). Then, we are overlapping the FileReader with the BufferedReader by sending the FileReader object fr to the constructor of the BufferedReader. We are going to make all the read request to the BufferedReader object ReadFileBuffer (Marked as 2). Using the "readLine()" method of the BufferedReader, we are reading all three line of texts (Marked as 3). Note that the readLine() method reads the line of text along with the newline character. So, when we print the readLine() return string in the console output window, the cursor goes to next line after printing the line. Finally, we are closing both the Readers by calling the "close()" method on the BufferedReader object ReadFileBuffer (Marked as 4).

4. Full Code Example

Below is the complete code example:

//Sample 01: Package inclusion
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.BufferedReader;


public class Main {
    public static void main(String[] args) {
        try
        {
            //Sample 01: Open the FileWriter, Buffered Writer
            FileWriter fw = new
                    FileWriter("C:\\Temp\\TestFile.Txt");
            BufferedWriter WriteFileBuffer = new
                    BufferedWriter(fw);

            //Sample 02: Write Some Text to File
            // Using Buffered Writer)
            WriteFileBuffer.write("First Line");
            WriteFileBuffer.newLine();
            WriteFileBuffer.write("Second Line");
            WriteFileBuffer.newLine();
            WriteFileBuffer.write("Third Line");
            WriteFileBuffer.newLine();

            //Sample 03: Close both the Writers
            WriteFileBuffer.close();

            //Sample 04: Open the Readers Now
            FileReader fr = new 
                    FileReader("C:\\Temp\\TestFile.txt");
            BufferedReader ReadFileBuffer = new 
                    BufferedReader(fr);

            //Sample 05: Read the text Written 
            // using BufferedWriter
            System.out.println(ReadFileBuffer.readLine());
            System.out.println(ReadFileBuffer.readLine());
            System.out.println(ReadFileBuffer.readLine());

            //Sample 06: Close the Readers
            ReadFileBuffer.close();

        } catch (IOException Ex)
        {
            System.out.println(Ex.getMessage());
        }
    }
}

Note: To run this example, make sure we have a folder called Temp in C:\ Root.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, owlcation.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://owlcation.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)