Wednesday, 9 May 2012

Read a file line by line in Java - Sample Program

This sample Java program demonstrates how to read a file in Java Line by Line. For this the following two classes DataInputStream and BufferedReader are used. This program can be used to read any text file line by line and process the contents of the file within a Java Program.
Class DataInputStream
A data input stream is use to read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.

Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification, Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.) Note that in the following tables, the most significant bit appears in the far left-hand column.

BufferedReader 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.



1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.io.*;

class FileRead {
 public static void main(String args[]) {
  try {
   // Open the file that is the first
   // command line parameter
   FileInputStream fstream = new FileInputStream("textfile.txt");
   // Get the object of DataInputStream
   DataInputStream in = new DataInputStream(fstream);
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
   String strLine;
   // Read File Line By Line
   while ((strLine = br.readLine()) != null) {
    // Print the content on the console
    System.out.println(strLine);
   }
   // Close the input stream
   in.close();
  } catch (Exception e) {// Catch exception if any
   System.err.println("Error: " + e.getMessage());
  }
 }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...