The Java Program: Iter.java

  1 import java.io.IOException;
  2 import java.io.InputStreamReader;
  3 import java.io.BufferedReader;
  4 
  5 import java.util.Iterator;
  6 import java.util.NoSuchElementException;
  7 
  8 /*
  9    The problem with string tokenizer is that
 10       field1;field2;;field4
 11    is the same as
 12        field1;field2;field3;
 13    So data with fixed columns is not easily parsable.  It is true that
 14    it can be done with 'new StreamTokenizer (line, ";", true)', but 
 15    that way is as hard or harder than the following.
 16 */
 17 
 18 public class Iter {
 19 
 20    public static Iterator parseFields (final String s, final char delim) {
 21 
 22       // a local class implementing the "Iterator" interface
 23       class Parser implements Iterator {
 24          private int pos = 0;
 25          public boolean hasNext() { return (pos<=s.length()); }
 26          public Object next() throws NoSuchElementException {
 27             final int l = s.length();
 28             if (pos>l) throw new NoSuchElementException();
 29             final int i = s.indexOf (delim, pos);
 30             final int e = (i==-1?l:i);   // if no delimiter, field goes to end of line
 31             String sub = s.substring (pos, e);
 32             pos = e+1;  // skip delimiter
 33             return sub;
 34          }
 35          public void remove() throws UnsupportedOperationException {
 36             throw new UnsupportedOperationException();
 37          }
 38       }
 39 
 40       return new Parser ();   // Could have used an anonymous inner class
 41    }
 42 
 43 
 44    public static void main (String args[]) throws IOException {
 45       final char delim = (args.length==1&&(args[0].length()==1))?args[0].charAt(0):':';
 46       final BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
 47 
 48       while (true) {
 49          final String line = br.readLine();
 50          if (line==null) break;
 51          int f = 1;
 52          for (Iterator i=parseFields (line, delim); i.hasNext(); ) {
 53             System.out.println ("Field " + (f++) + "  '" + i.next() + "'");
 54          }
 55          System.out.println();
 56       }
 57    }
 58 }