黑马程序员技术交流社区

标题: 入学考试题4 [打印本页]

作者: houweicheng    时间: 2015-8-15 22:51
标题: 入学考试题4
自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时,能够在读取的每行前面都加上有行号和冒号。

public class Test5 {
        public static void main(String[] arg) {
                Reader textReader = null;
                try {
                        textReader=new FileReader("ForTest5Read.txt");
                        packStringStream pss=new packStringStream(textReader);
                        String toprint;
                        while ((toprint=pss.packedReadline())!=null) {
                                System.out.println(toprint);
                        }
                } catch (FileNotFoundException e) {
                        // TODO 自动生成的 catch 块
                        System.out.println("读取失败可能文件不存在");
                }
                catch (IOException e) {
                        System.out.println("文件读取失败");
                }
                finally
                {
                        if (textReader!=null) {
                                try {
                                        textReader.close();
                                } catch (IOException e) {
                                        // TODO 自动生成的 catch 块
                                        System.out.println("文件关闭失败");
                                }
                        }
                }
               
               
        }
}

class packStringStream
{
        BufferedReader br;
        Integer count=0;
        public packStringStream(Reader r) {
                br=new BufferedReader(r);
        }
       
        public String packedReadline() throws IOException {
               
                String string=null;
                StringWriter sw=new StringWriter();
                if((string=br.readLine())!=null) {
                        count++;
                        sw.write(count.toString());
                        sw.write(":");
                        sw.write(string);
                }
                else {
                        return null;
                }
                return sw.toString();
        }
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2