- package com.itheima;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- /**
- * 第5题:自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时,
- * 能够在读取的每行前面都加上有行号和冒号。
- *
- * @author hp-pc
- *
- * */
- class MyStream
- {
- // 定义缓冲字符输入流
- BufferedReader read;
- // 定义一个可变的字符序列
- StringBuilder sb;
- MyStream(BufferedReader read)
- {
- this.read = read;
- pack();
- }
- // 通过文件路径构造
- MyStream(String path) throws FileNotFoundException
- {
- this(new BufferedReader(new FileReader(path)));
- }
- /*// 通过文件对象构造
- public MyStream(File file) throws FileNotFoundException
- {
- this(new BufferedReader(new FileReader(file)));
- }*/
- // 对读入的每一行按照要求处理
- private void pack()
- {
- //new一个缓冲字符输入流
- sb = new StringBuilder();
- //初始化行号为0
- int lineNumber = 0;
- //初始化读取的一行的值为null
- String lineStr = null;
- try
- {
- while ((lineStr = read.readLine()) != null)
- {
- //把读取的每一行加上行号和冒号
- sb.append(++lineNumber + ":" + lineStr + "\n");
- }
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- //对处理后的字符串打印
- public void print()
- {
- System.out.println(sb.toString());
- }
- }
- public class Test5
- {
- public static void main(String[] args)
- {
- try
- {
- MyStream ms = new MyStream("src\\com\\itheima\\Test1.java");
- ms.print();
- }
- catch (FileNotFoundException e)
- {
- e.printStackTrace();
- }
- }
- }
复制代码 |
|