001// Copyright (c) 2001 Hursh Jain (http://www.mollypages.org) 
002// The Molly framework is freely distributable under the terms of an
003// MIT-style license. For details, see the molly pages web site at:
004// http://www.mollypages.org/. Use, modify, have fun !
005
006package fc.io;
007
008import java.io.*;
009import java.util.*;
010import java.util.regex.*;
011import java.lang.reflect.*;
012import fc.util.*;
013
014/** 
015Extends the {@link java.io.BufferedReader#readLine readLine} functionality of {@link java.io.BufferedReader BufferedReader} by ignoring  any commented and empty lines.
016<p>
017<ul>
018<li>comments start with <code>#</code> or <code>//</code></li>
019<li>empty lines consist of only 0 or more whitespace</li>
020</ul>
021**/
022public class CommentedFileReader extends BufferedReader
023{
024private static final boolean dbg = false;
025
026/** 
027Reads from the specified Reader
028
029@throws IOException   on error reading from the file
030*/
031public CommentedFileReader(Reader r) throws IOException
032  {
033  super(r);
034  }
035  
036/** 
037Reads from the specified file, using UTF-8 encoding.
038
039@throws IOException   on error reading from the file
040*/
041public CommentedFileReader(File f) throws IOException
042  {
043    super(new InputStreamReader(new FileInputStream(f), "UTF-8"));
044  } 
045  
046public String readLine() throws IOException
047  {
048  String line = super.readLine();
049  
050  while (shouldSkip(line)) {
051    if (dbg) System.out.println("Skipping: " + line);
052    line = super.readLine();
053    }
054    
055  return line;
056  }
057
058protected boolean shouldSkip(String line)
059  {
060  //don't skip null, caller can then return null instead
061  if (line == null) 
062    return false;
063    
064  String trimline = line.trim();
065
066  return trimline.length() == 0 
067        || trimline.startsWith("#") 
068        || trimline.startsWith("//");
069  }
070
071public static void main (String args[]) throws IOException
072  {
073  Args myargs = new Args(args);
074  String filestr = myargs.getRequired("file");
075  CommentedFileReader cr = new CommentedFileReader(new File(filestr));
076  String line = null;
077  while ((line = cr.readLine()) != null) {
078    System.out.println(line);
079    }
080  }
081}