设计一个输入流,该类的作用是在读文件的时候把文件中的大写字母转换为小写,小写转换为大写,数字不变

可以通过继承抽象装饰者类(FilterInputStream)实现一个装饰类,通过调用InputStream类或其子类提供的了一些方法再加上逻辑判断实现该功能。

import java.io.*;

/**
 * Created by Administrator on 2018/4/25 0025.
 */
public class MyOwnInputStream extends FilterInputStream{
    public static void main(String[] args) {
        int c;
        try {
            InputStream is = new MyOwnInputStream(new FileInputStream("D:/test.txt"));
            while ((c = is.read()) >= 0) {
                System.out.println((char) c);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public MyOwnInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        int c = super.read();
        if (c != -1) {
            if (Character.isLowerCase((char)c)) {
                return Character.toUpperCase((char) c);
            }
            else if (Character.isUpperCase((char)c)) {
                return Character.toLowerCase((char) c);
            }
            else {
                return c;
            }
        } else {
            return -1;
        }

    }

}

参考文献 Java程序员面试笔试宝典 P117

猜你喜欢

转载自blog.csdn.net/qq_31617121/article/details/80073263
今日推荐