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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. package com.itheima;

  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.io.IOException;

  7. /**
  8. * 第5题:自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时,
  9. * 能够在读取的每行前面都加上有行号和冒号。
  10. *
  11. * @author hp-pc
  12. *
  13. * */

  14. class MyStream
  15. {
  16.         // 定义缓冲字符输入流
  17.         BufferedReader read;
  18.         // 定义一个可变的字符序列
  19.         StringBuilder sb;

  20.         MyStream(BufferedReader read)
  21.         {
  22.                 this.read = read;
  23.                 pack();
  24.         }

  25.         // 通过文件路径构造
  26.         MyStream(String path) throws FileNotFoundException
  27.         {
  28.                 this(new BufferedReader(new FileReader(path)));
  29.         }

  30.         /*// 通过文件对象构造
  31.         public MyStream(File file) throws FileNotFoundException
  32.         {
  33.                 this(new BufferedReader(new FileReader(file)));
  34.         }*/

  35.         // 对读入的每一行按照要求处理
  36.         private void pack()
  37.         {
  38.                 //new一个缓冲字符输入流
  39.                 sb = new StringBuilder();
  40.                 //初始化行号为0
  41.                 int lineNumber = 0;
  42.                 //初始化读取的一行的值为null
  43.                 String lineStr = null;
  44.                 try
  45.                 {

  46.                         while ((lineStr = read.readLine()) != null)
  47.                         {
  48.                                 //把读取的每一行加上行号和冒号
  49.                                 sb.append(++lineNumber + ":" + lineStr + "\n");
  50.                         }
  51.                 }
  52.                 catch (IOException e)
  53.                 {
  54.                         e.printStackTrace();
  55.                 }
  56.         }

  57.         //对处理后的字符串打印
  58.         public void print()
  59.         {
  60.                 System.out.println(sb.toString());
  61.         }

  62. }

  63. public class Test5
  64. {
  65.         public static void main(String[] args)
  66.         {
  67.                 try
  68.                 {
  69.                         MyStream ms = new MyStream("src\\com\\itheima\\Test1.java");
  70.                         ms.print();
  71.                 }
  72.                 catch (FileNotFoundException e)
  73.                 {
  74.                         e.printStackTrace();
  75.                 }
  76.         }

  77. }
复制代码

1 个回复

倒序浏览
学习学习
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马