Creating a BufferedReader BufferedReader is not a subclass of FileInputStream BufferedReader collaborates with an object of class InputStreamReader The object of class InputStreamReader collaborates with an object of class InputStream Why does it have to be so complicated? There are two reasons. First, if BufferedReader were a subclass of FileInputStream it would be good for file handling, but it would not help with other data that was in stream format (e.g., data from the keyboard or network). We would have to implement the same code as subclasses of many different classes. This is inefficient. Second, Java does not see a String as being comprised of bytes, but of characters. In most programming languages a character and a byte are the same, but not in Java. So heres how we create a BufferedReader that will allow us to read the file readme.txt one line at a time: File aFile = new File ("readme.txt"); FileInputStream fis = new FileInputStream (aFile); InputStreamReader isr = new InputStreamReader (fis); BufferedReader br = new BufferedReader(isr); String aLine = br.readLine();
Note that four different classes are involved in this simple method! This is what happens when the program executes br.readLine() . 1. The BufferedReader asks the InputStreamReader for the next character. 2. The InputStreamReader asks the FileInputStream for the next byte 3. The FileInputStream gets the byte from the file specified by the File object 4. The InputStreamReader converts the byte to a characters, and passes it along to the BufferedReader 5. The bufferedReader checks whether the character is an end-of-line indicator. If it is then the line is complete. Otherwise repeat from step one. Of course all this complication is hidden from the programmer the explanation has been included so that you can see what the four classes do. Reading a text file a line at a time is such a common method that it is surprising that Java does not contain a class to automate it. Some proprietary Java development tools include extended class libraries that have this sort of facility. For example, Microsofts Visual J++ has a class called TextReader that does exactly this job. However, it is simple enough to implement a TextReader class yourself and use it in any program that requires this facility. The process described above can be simplified slightly by the use of the FileReader class. Back to top 
RITSEC - Global Campus Copyright ?1999 RITSEC- Middlesex University. All rights reserved. webmaster@globalcampus.com.eg |