Home arrow Java arrow Working with Text Files and File Name Filters in Java

Working with Text Files and File Name Filters in Java

This article, the third of three parts, will teach you how the programs you create in Java can interact with different storage devices using a communications system called streams. It is excerpted from chapter 15 of the book Sams Teach Yourself Java 2 in 21 days, written by Roger Cadenhead and Laura Lemay (Sams, ISBN: 0672326280)

Author Info:
By: Sams Publishing
Rating: 5 stars5 stars5 stars5 stars5 stars / 9
April 27, 2006
  1. · Working with Text Files and File Name Filters in Java
  2. · Writing Text Files
  3. · Files and Filename Filters
  4. · Summary
  5. · Quiz

print this article

Working with Text Files and File Name Filters in Java
(Page 1 of 5 )

Reading Text Files

FileReader is the main class used when reading character streams from a file. This class inherits from InputStreamReader, which reads a byte stream and converts the bytes into integer values that represent Unicode characters.

A character input stream is associated with a file using the FileReader(String) constructor. The string indicates the file, and it can contain path folder references in addition to a filename.

The following statement creates a new FileReader called look and associates it with a text file called index.txt:

FileReader look = new FileReader("index.txt");

After you have a file reader, you can call the following methods on it to read characters from the file:

  • read() returns the next character on the stream as an integer.

  • read(char[], int, int) reads characters into the specified character array with the indicated starting point and number of characters read.

The second method works like similar methods for the byte input stream classes. Instead of returning the next character, it returns either the number of characters that were read or –1 if no characters were read before the end of the stream was reached.

The following method loads a text file using the FileReader object text and displays its characters:

FileReader text = new FileReader("readme.txt");
int inByte;
do {
inByte = text.read();
if (inByte != -1)
System.out.print( (char)inByte );
} while (inByte != -1);

Because a character stream's read() method returns an integer, you must cast this to a character before displaying it, storing it in an array, or using it to form a string. Every character has a numeric code that represents its position in the Unicode character set. The integer read off the stream is this numeric code.

If you want to read an entire line of text at a time instead of reading a file character by character, you can use the BufferedReader class in conjunction with a FileReader.

The BufferedReader class reads a character input stream and buffers it for better efficiency. You must have an existing Reader object of some kind to create a buffered version. The following constructors can be used to create a BufferedReader:

  • BufferedReader(Reader)—Creates a buffered character stream associated with the specified Reader object, such as FileReader

  • BufferedReader(Reader, int)—Creates a buffered character stream associated with the specified Reader and with a buffer of int size

A buffered character stream can be read using the read() and read(char[], int, int) methods described for FileReader. You can read a line of text using the readLine() method.

The readLine() method returns a String object containing the next line of text on the stream, not including the character or characters that represent the end of a line. If the end of the stream is reached, the value of the string returned will be equal to null.

An end-of-line is indicated by any of the following:

  • A newline character ('\n')

  • A carriage return character ('\r')

  • A carriage return followed by a newline ("\n\r")

The project contained in Listing 15.7 is a Java application that reads its own source file through a buffered character stream.

Listing 15.7 The Full Text of ReadSource.java

 1: import java.io.*;
3: public class ReadSource {
4:   public static void main(String[] arguments) {
5:     try {
6:       FileReader file = new
7:         FileReader("ReadSource.java");
8:       BufferedReader buff = new
9:         BufferedReader(file);
10:       boolean eof = false;
11:       while (!eof) {
12:         String line = buff.readLine();
13:         if (line == null)
14:           eof = true;
15:         else
16:           System.out.println(line);
17:       }
18:       buff.close();
19:     } catch (IOException e) {
20:       System.out.println("Error -- " +
e.toString()); 21: } 22: } 23: }

Much of this program is comparable to projects created earlier today, as illustrated:

  • Lines 6 and 7—An input source is created: the FileReader object associated with the file ReadSource.java.

  • Lines 8 and 9—A buffering filter is associated with that input source: the BufferedReader object buff.

  • Lines 11–17—A readLine() method is used inside a while loop to read the text file one line at a time. The loop ends when the method returns the value null.

The ReadSource application's output is the text file ReadSource.java.

blog comments powered by Disqus

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2019 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials