Use FileReader and BufferedReader to read text from a character-input stream

Home arrow Java Tutorials arrow Source code arrow Use FileReader and BufferedReader to read text from a character-input stream
Use FileReader and BufferedReader to read text from a character-input stream Print E-mail
Contributed by Howell   
Monday, 12 June 2006

Read text from a character-input stream, buffering 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. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

 BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));
 will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.

Below is an example


import java.io.*;
public class ReadFile
  {
  public static void main(String args[]) throws Exception
    {
    BufferedReader br = new BufferedReader(
                        new FileReader("birds.txt"));
    String s;
    while (br.ready())
      {
      s=br.readLine();
      System.out.println("Bird ="+s);
      }
    }
  }


A example of writing file


import java.io.*;
public class WriteFile
  {
  public static void main(String args[]) throws Exception
    {
    BufferedReader br=new BufferedReader(
                      new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(
                        new FileWriter("line.txt"));
    String s;
    while (true)
      {
      System.out.flush();
      s=br.readLine();
      if (s.length()==0) break;
      bw.write(s);
      bw.newLine();
      }
    bw.close();
    }
  }

 

Last Updated ( Tuesday, 08 August 2006 )

  home              contact us

 

©2006-2008 DeveloperZone.biz   All rights reserved     powered by Mambo Designed by Siteground