由Java基础笔记 – IO流分类详细介绍和各种字节流类介绍与使用 过滤流 字节流2.2.1、字节输出流的抽象类及其最关键的方法,可知,只有最后一个方法才是抽象的,原因是前面两个都调用了第三个抽象方法,这样继承这个抽象类的子类都必须提供抽象的write(int b)的实现,从而使得每个子类的实现都不一样。
所以这样我们就可以编写自己的IO流类了,只要继承InputStream类并实现其中的抽象方法:
abstract void write(int b)。
而其他两个已实现的方法会自动调用这个抽象方法的实现方法。
自定义一个字节数组:
1、实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
public class MyInputStream extends InputStream {
protected byte[] data; protected int ptr = 0; public MyInputStream(byte[] data){ this.data = data; } @Override public int read() throws IOException { if(ptr < data.length) return data[ptr++]; else return -1; } }
|
2、调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public static void main(String[] args) throws IOException { String name = "abcdefg"; byte[] b = name.getBytes();
MyInputStream mis = new MyInputStream(b); while(true){ int c = mis.read(); if(c == -1){ break; } System.out.println(c); } }
|