inputstream(InputStream详解)

时间:2022-12-15 浏览:67 分类:百科

1、InputStream:字节输入流,可以将磁盘中的文件读取到java程序中;InputStream是所有字节输入流的顶级父类,它是一个抽象类,如果要用,需要使用其子类;

2、InputStream类结构组成


public abstract class InputStream implements Closeable {

/**
1、从输入流中读取下一个字节的数据,一个字节一个字节的读
2、返回值int是读取字节对应的int值
3、如果返回值int= -1,那么说明已经读取完成
*/
public abstract int read() throws IOException;

/**
1、将输入流中读取的数据放入byte数组中
2、返回值int是读取字节的长度
3、如果返回值int= -1,那么说明已经读取完成
*/
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}

public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return 0;
}

int c = read();
if (c == -1) {
return -1;
}
b[off] = (byte)c;

int i = 1;
try {
for (; i < len ; i++) {
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte)c;
}
} catch (IOException ee) {
}
return i;
}

3、InputStream常用的子类

1、FileInputStream:文件输入流

2、BufferedInputStream:换成字节输入流

3、ObjectInputStream:对象字节输入流

发表评论