001    /*
002    
003      Copyright (C) 2001 Laurent Martelli
004    
005      This program is free software; you can redistribute it and/or modify
006      it under the terms of the GNU Lesser General Public License as
007      published by the Free Software Foundation; either version 2 of the
008      License, or (at your option) any later version.
009    
010      This program is distributed in the hope that it will be useful,
011      but WITHOUT ANY WARRANTY; without even the implied warranty of
012      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013      GNU Lesser General Public License for more details.
014    
015      You should have received a copy of the GNU Lesser General Public License
016      along with this program; if not, write to the Free Software
017      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
018    
019    package org.objectweb.jac.util;
020    
021    import java.io.FilterWriter;
022    import java.io.Writer;
023    import java.io.IOException;
024    
025    /**
026     * A writer which counts the numbers of lines that it writes.
027     *
028     * @see #getLines()
029     */
030    
031    public class LineNumberWriter extends FilterWriter
032    {
033       // last read byte
034       int last = -1;
035       int lines = 1;
036    
037       public LineNumberWriter(Writer out) {
038          super(out);
039       }
040    
041       public void write(int b) throws IOException {
042          if ( (b == '\r' && last != '\n') || 
043               (b=='\n') ) {
044             lines++;
045          }
046          out.write(b);
047          last = b;
048       }
049    
050       public void write(char[] b, int off, int len) throws IOException
051       {
052          while (len-- > 0) {
053             write(b[off++]);
054          }
055       }
056    
057       public void write(String str, int off, int len) throws IOException
058       {
059          while (len-- > 0) {
060             write(str.charAt(off++));
061          }
062       }
063    
064       /**
065        * Returns the number of lines written
066        */
067       public int getLines() {
068          return lines;
069       }
070    }
071