随笔 - 117  文章 - 72  trackbacks - 0

声明:原创作品(标有[原]字样)转载时请注明出处,谢谢。

常用链接

常用设置
常用软件
常用命令
 

订阅

订阅

留言簿(7)

随笔分类(130)

随笔档案(123)

搜索

  •  

积分与排名

  • 积分 - 152591
  • 排名 - 390

最新评论

[关键字]:java,design pattern,设计模式,《Java与模式》学习,decorator,装饰模式,Unix
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com)
[正文]:

package pattern.decorator.grep;

import java.io.*;

/**
 * 装饰模式(Decorator Pattern):Grep
 *
 * Grep是UNIX中的命令,
 * 使用命令"grep BMW file",
 * 就可以在file中找出含有BMW的行,并显示。
 *
 * @version 2009-6-6
 * @author Winty(wintys@gmail.com)
 */
public class Grep{
    public static void main(String[] args)throws Exception{
        GrepView view = new GrepView();

        if(args.length < 2){
            view.println("Usage: java Grep targetString fileName");
            view.println("e.g.:java Grep BMW C:/sample.txt");
            System.exit(0);
        }
        
        GrepReader grep;

        FileReader file = new FileReader(args[1]);
        grep = new GrepReader(file , args[0] , view);
        grep.search();
    }
}

class GrepReader extends FilterReader{
    private LineNumberReader reader;
    private String target;
    private GrepView view;

    /**
     *@param in 在输入流in中查找目标字符串
     *@param target 要查找的目标字符串
     *@param view 查找结果输出
     */
    public GrepReader(Reader in , String target , GrepView view){
        super(in);
        reader = new LineNumberReader(in);
        this.target = target;
        this.view = view;
    }

    public void search()throws Exception{
        String line = null;
        while((line = reader.readLine())!=null){
            int index = -1;
            if((index = line.indexOf(target)) != -1){
                String str;
                str = "line" + reader.getLineNumber() + " column" + (index +1) +":" + line;
                view.println(str);
            }
        }

        reader.close();
    }
}

class GrepView{
    private PrintStream out;

    public GrepView(){
        this.out = System.out;
    }

    public void println(String str){
        out.println(str);
    }
}
posted on 2009-06-07 22:42 天堂露珠 阅读(981) 评论(2)  编辑  收藏 所属分类: Pattern

FeedBack:
# re: [原]装饰模式3-Grep 2009-06-07 23:22 subtitle
good....  回复  更多评论
  
# re: [原]装饰模式3-Grep 2009-06-08 08:20 网络小说
ver ygood  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: