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<ul>
017<li>comments start with <code>#</code> or <code>//</code></li>
018<li>empty lines consist of only 0 or more whitespace</li>
019</ul>
020**/
021public class CommentedFileReader extends BufferedReader
022{
023private static final boolean dbg = false;
024
025/** 
026Reads from the specified Reader
027
028@throws IOException   on error reading from the file
029*/
030public CommentedFileReader(Reader r) throws IOException
031  {
032  super(r);
033  }
034  
035/** 
036Reads from the specified file, using UTF-8 encoding.
037
038@throws IOException   on error reading from the file
039*/
040public CommentedFileReader(File f) throws IOException
041  {
042    super(new InputStreamReader(new FileInputStream(f), "UTF-8"));
043  } 
044  
045public String readLine() throws IOException
046  {
047  String line = super.readLine();
048  
049  while (shouldSkip(line)) {
050    if (dbg) System.out.println("Skipping: " + line);
051    line = super.readLine();
052    }
053    
054  return line;
055  }
056
057protected boolean shouldSkip(String line)
058  {
059  //don't skip null, caller can then return null instead
060  if (line == null) 
061    return false;
062    
063  String trimline = line.trim();
064
065  return trimline.length() == 0 
066        || trimline.startsWith("#") 
067        || trimline.startsWith("//");
068  }
069
070public static void main (String args[]) throws IOException
071  {
072  Args myargs = new Args(args);
073  String filestr = myargs.getRequired("file");
074  CommentedFileReader cr = new CommentedFileReader(new File(filestr));
075  String line = null;
076  while ((line = cr.readLine()) != null) {
077    System.out.println(line);
078    }
079  }
080}