image
 
image
CharIterator.java


/*::.
==================================================================================================================================
=================================================¦ Copyright © 2003 Allen Baker ¦=================================================
                                                 +------------------------------+
File:       CharIterator.java
Originator: Allen Baker (2003.12.30)
LayoutRev:  5
================================================================================================================================== */



/*.
==========================================================================================
Package
------------------------------------------------------------------------------------------ */
package cosmicabyss.com.lib;



/*.
==========================================================================================
Imports
------------------------------------------------------------------------------------------ */
import java.io.*;
import java.util.*;



/*::
======================================================================================================================== *//**
Instances of this class are Iterators over the characters in a text file. The text file is treated as an ordered list of
chars. This provides an alternative and cleaner paradigm (an iterator pattern) for reading a text file one character at
a time from the one provided by the BufferedReader or TextReader class.

<P>
   <DL>
      <DT>
         <B>
            Example usage:
         </B>
         <DD>
            <BLOCKQUOTE>
               <PRE id="unindent">
                  ==============================================
                  Use a CharIterator to iterate through the chars of a text file
                  and copy the contents to stdout.
                  ----------------------------------------------
                  CharIterator iter = new CharIterator(pArgs[0]);

                  while (iter.hasNext())
                     {
                     char c = iter.next();
                     System.out.print(c);;
                     }
               </PRE>
            </BLOCKQUOTE>
         </DD>
      </DT>
      <DT>
         <B>
            View Source:
         </B>
         <DD>
            <A href="CharIterator.java.html">
               CharIterator.java
            </A>
         </DD>
      </DT>
      <DT>
         <B>
            Author:
         </B>
         <DD>
            <A href="mailto:sourcecode.v01@cosmicabyss.com">
               Allen Baker
            </A>
         </DD>
      </DT>
   </DL>
*//*
======================================================================================================================== */
public class CharIterator
   {



   /*:                                    :METHOD:000:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method creates a new CharIterator, given the File to read from.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#000">View source</A>

   @param
      pFile is the file to read from.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public CharIterator(File pFile) throws Exception
      {
      /*.
      ==========================================================================================
      A new object of this class always opens another instance of the file for reading
      ------------------------------------------------------------------------------------------ */
      iIter = new TextReaderIterator(pFile);
      /*.
      ==========================================================================================
      Put the new object into its initialized state.
      ------------------------------------------------------------------------------------------ */
      initialize();
      }



   /*:                                    :METHOD:001:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method creates a new CharIterator, given an InputStream (such as System.in) to read from.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#001">View source</A>

   @param
      pInputStream is the InputStream to read from.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public CharIterator(InputStream pInputStream) throws Exception
      {
      /*.
      ==========================================================================================
      A new object of this class always opens another instance of the file for reading
      ------------------------------------------------------------------------------------------ */
      iIter = new TextReaderIterator(pInputStream);
      /*.
      ==========================================================================================
      Put the new object into its initialized state.
      ------------------------------------------------------------------------------------------ */
      initialize();
      }



   /*:                                    :METHOD:002:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method creates a new CharIterator, given the name of the file to read from.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#002">View source</A>

   @param
      pFileName is the name of the file to read from.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public <Type> CharIterator(Type pFileName) throws Exception
      {
      /*.
      ==========================================================================================
      A new object of this class always opens another instance of the file for reading
      ------------------------------------------------------------------------------------------ */
      iIter = new TextReaderIterator(pFileName);
      /*.
      ==========================================================================================
      Put the new object into its initialized state.
      ------------------------------------------------------------------------------------------ */
      initialize();
      }



   /*:                                    :METHOD:003:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method returns true if the iteration has more elements. (In other words, returns true if next
   would return an element rather than throwing an exception.)

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#003">View source</A>

   @return
      True if the iterator has more elements.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public boolean hasNext()
      {
      return (iNext < iLength);
      }



   /*:                                    :METHOD:004:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method returns the next element in the iteration but does not move the iterator ahead. This
   means that the next time peek() or next() is called, the same Sting is returned again.<P>

   If there's no next element, this method throws a NoSuchElementException. To avoid this exception,
   the user should always call hasNext() to test whether or not the iteration has a next element before
   calling this method.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#004">View source</A>

   @return
      The next element in the iteration.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public char peek() throws NoSuchElementException
      {
      /*.
      ==========================================================================================
      If there's no next char, the user shouldn't have called this method. Throw an exception.
      ------------------------------------------------------------------------------------------ */
      if ( ! this.hasNext())
         {
         throw new NoSuchElementException();
         }
      /*.
      ==========================================================================================
      Return the next char
      ------------------------------------------------------------------------------------------ */
      return iBuffer.charAt(iNext);
      }



   /*:                                    :METHOD:005:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method returns the next element in the interation.<P>

   If there's no next element, this method throws a NoSuchElementException. To avoid this exception,
   the user should always call hasNext() to test whether or not the iteration has a next element before
   calling this method.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#005">View source</A>

   @return
      The next element in the iteration.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public char next() throws NoSuchElementException
      {
      /*.
      ==========================================================================================
      If there's no next char, the user shouldn't have called this method. Throw an exception.
      ------------------------------------------------------------------------------------------ */
      if ( ! this.hasNext())
         {
         throw new NoSuchElementException();
         }
      /*.
      ==========================================================================================
      Get the next char and then advance the iterator
      ------------------------------------------------------------------------------------------ */
      char  ch = iBuffer.charAt(iNext);
      iNext++;
      /*.
      ==========================================================================================
      Return the next char
      ------------------------------------------------------------------------------------------ */
      return ch;
      }



   /*:                                    :METHOD:006:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method is not implemented. It is an optional method in the Iterator interface that removes from
   the underlying collection the last element returned by the iterator. If this method is called it
   will throw an UnsupportedOperationException.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#006">View source</A>

   *//*
   ---------------------------------------------------------------------------------------------------- */
   public void remove() throws UnsupportedOperationException
      {
      throw new UnsupportedOperationException();
      }



   /*:                                    :METHOD:007:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method sets the ConsoleStream for this object.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#007">View source</A>

   @return
      A reference to this object

   @param
      pConsole is a ConsoleStream through which this objects sends its output.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public CharIterator setOut(ConsoleStream pConsole)
      {
      cOut = pConsole;
      return this;
      }



   /*:                                    :METHOD:008:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This boilerplate method is used for testing an instantiated object of this class and may include any
   code the developer chooses.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#008">View source</A>

   *//*
   ---------------------------------------------------------------------------------------------------- */
   public CharIterator test() throws Exception
      {
      cOut.titledPrintf
         (
         "\"HELLO WORLD!\"",
         "%s  %s  %s",
         "I'm an object of the", CLASS_NAME, "class, and I approved this message."
         );
      return this;
      }



   /*:.
   ==============================================================================================================
   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[  Protected  ]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   ============================================================================================================== */



   /*:.
   ==============================================================================================================
   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[  Private  ]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   ============================================================================================================== */



   /*.
   ==========================================================================================
   Class Constants
      CLASS_NAME : the name of this class DFLT_LINE_LEN : the default line length for word
      wrapping
   ------------------------------------------------------------------------------------------ */
   private static final XString  CLASS_NAME    = new XString(CharIterator.class.getName());
   private static final int      DFLT_LINE_LEN = ConsoleMessage.defaultLineLength();
   /*.
   ==========================================================================================
   Class variables
      cOut : console output.
   ------------------------------------------------------------------------------------------ */
   private static ConsoleStream  cOut = ConsoleStream.getSingleton();
   /*.
   ==========================================================================================
   Instance variables
   ------------------------------------------------------------------------------------------ */
   /*.
   ==========================================================================================
   Each instance of this object creates an instance of a TextReaderIterator (iIter) for
   reading the underlying file. In order for the hasNext() method to work, the next line in
   the file is always prefetched and stored in iNext.
   ------------------------------------------------------------------------------------------ */
   private TextReaderIterator  iIter;
   private StringBuffer        iBuffer;
   private int                 iNext;
   private int                 iLength;



   /*:                                    :METHOD:009:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method puts an object into its initial state.

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#009">View source</A>

   *//*
   ---------------------------------------------------------------------------------------------------- */
   private void initialize() throws Exception
      {
      iBuffer = new StringBuffer();
      while (iIter.hasNext())
         {
         iBuffer.append((XString)iIter.next());
         iBuffer.append('\n');
         }
      iNext   = 0;
      iLength = iBuffer.length();
      }



   /*:.
   ==============================================================================================================
   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[  Inner Classes  ]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   ============================================================================================================== */



   /*:.
   ==============================================================================================================
   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[  Public Static Methods  ]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   ============================================================================================================== */



   /*:                                    :METHOD:010:BOOKMARK:
   ====================================================================================================
   [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]
   ==================================================================================================== *//**
   This method allows this class file to be unit tested as a standalone application. It's the method
   that's called when the class is invoked from the command line by using the java application launcher
   - "java". Main() is not a required method, but the practice of putting one in each class and
   wrapping class test code within it allows easy unit testing of the class; and main does not need to
   be removed when testing is complete.

   <P>
      <DL>
         <DT>
            <B>
               Command line usage:
            </B>
            <DD>
               Java cosmicabyss.com.lib.CharIterator
            </DD>
         </DT>
      </DL>

   <P><B>Implementation: </B><A HREF="CharIterator.java.html#010">View source</A>

   @param
      pArgs contains the command line arguments with which this class was invoked as an application.
   *//*
   ---------------------------------------------------------------------------------------------------- */
   public static void main(String[] pArgs) throws Exception
      {
      /*.
      ==========================================================================================
      Greetings !
      ------------------------------------------------------------------------------------------ */
      cOut.banner(CLASS_NAME);
      /*.
      ==========================================================================================
      Gotta say what file to read
      ------------------------------------------------------------------------------------------ */
      if (pArgs.length < 1)
         {
         cOut.println
            (
            "usage: java com.adbaker.util.CharIterator inputFileName"
            );
         System.exit(-1);
         }
      /*.
      ==========================================================================================
      Use a CharIterator to iterate through the chars of a text file and copy the contents to
      stdout.
      ------------------------------------------------------------------------------------------ */
      CharIterator iter = new CharIterator(pArgs[0]);
      iter.test();

      while (iter.hasNext())
         {
         char c = iter.next();
         System.out.print(c);;
         }
      }



   }  // class CharIterator



   /*:.
   ==============================================================================================================
   @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@[  Notes  ]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
   ============================================================================================================== */