Java
  Home arrow Java arrow Working with Text Files and File Name Filt...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Working with Text Files and File Name Filters in Java
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2006-04-27

    Table of Contents:
  • Working with Text Files and File Name Filters in Java
  • Writing Text Files
  • Files and Filename Filters
  • Summary
  • Quiz

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Working with Text Files and File Name Filters in Java


    (Page 1 of 5 )

    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)

    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);
    System.out.println("");
    text.close();

    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.*;
    2:
    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.

    More Java Articles
    More By Sams Publishing


       · This article is an excerpt from the book "Sams Teach Yourself Java 2 in 21 days,"...
     

    Buy this book now. This article 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). Check it out today at your favorite bookstore. Buy this book now.

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway
    Stay green...Green IT