Java基础笔记 - 继承InputStream自定义一个简单的字节数组输入流

发布于 2011-10-22 | 更新于 2020-09-20

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
/**
* 自定义一个字节数组输入流类
* @author arthinking
*/
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";
//这里保存的是字符的ascII码
byte[] b = name.getBytes();

MyInputStream mis = new MyInputStream(b);
while(true){
int c = mis.read();
if(c == -1){
break;
}
System.out.println(c);
}
}

本文作者: arthinking

本文链接: https://www.itzhai.comjava-based-notebook-a-custom-inputstream-inherits-a-simple-byte-array-input-stream.html

版权声明: 版权归作者所有,未经许可不得转载,侵权必究!联系作者请加公众号。

×
IT宅

关注公众号及时获取网站内容更新。