A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© houweicheng 中级黑马   /  2015-8-15 22:51  /  323 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个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();
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马