Sunday, August 25, 2013

Example of Decorator Pattern - LineNumberScanner

Create a LineNumberScanner like this

public class LineNumberScanner implements Iterator<String>
{
    Scanner sc;
    int i = 1;
    public LineNumberScanner(Scanner sc)
    {
        this.sc = sc;
    }

    public boolean hasNextLine() {
        return sc.hasNextLine();
    }

    public String nextLine() {
        String nextLine = sc.nextLine();
        if(nextLine==null) return nextLine;
        else
        {
            return (i++)+":"+nextLine;
        }
    }

    @Override
    public void remove() {
        sc.remove();
    }

    @Override
    public boolean hasNext() {
        return sc.hasNext();
    }

    @Override
    public String next() {
        return sc.next();
    }
    public void close()
    {
        sc.close();
    }
}

Use the code as follows

public static void main(String[] args) throws FileNotFoundException 
    {
        File file = new File("D:\\Yogesh.txt");
        FileInputStream fis = new FileInputStream(file);
        Scanner sc = new Scanner(fis);
        LineNumberScanner lineScanner = new LineNumberScanner(sc);
        while(lineScanner.hasNextLine())
        {
            System.out.println(lineScanner.nextLine());
        }
    }

No comments:

Post a Comment