-1不是流中写入的数据。read()方法返回的数据都是unsigned byte,即是[0,255]。底层实现有很多,比如socket IO和文件IO,甚至你自己也可以实现。
——————————————————————
给两个类的代码给你看看,理解一下这个东西:
/**
* 能随时获取读取了多少字节数据的InputStream
*/
public class LengthAwareInputStream extends FilterInputStream {
private volatile long length;
private long maxReadSize;
public LengthAwareInputStream(InputStream in) {
this(in, Long.MAX_VALUE);
}
public LengthAwareInputStream(InputStream in, long maxReadSize) {
super(in);
this.maxReadSize = maxReadSize;
}
@Override
public int read() throws IOException {
//读取长度超过最大值,用于检查流量
if (length + 1 > maxReadSize) {
throw new IOException("exceeded max read size: " + maxReadSize);
}
int ret = super.read();
if (ret >= 0) {
length++;
}
return ret;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
//读取长度超过最大值,用于检查流量
if (length + len > maxReadSize) {
throw new IOException("exceeded max read size: " + maxReadSize);
}
int ret = super.read(b, off, len);
if (ret > 0) {
length += ret;
}
return ret;
}
public long getLength() {
return length;
}
}
/**
* 读取数据达到特定长度之后自动终止(即返回-1)
* Created by Weijun on 2017/2/23.
*/
public class LengthLimitedInputStream extends LengthAwareInputStream {
private final long limitBytes;
/**
* @param in
* @param limitBytes
*/
public LengthLimitedInputStream(InputStream in, long limitBytes) {
super(in);
this.limitBytes = limitBytes;
}
@Override
public int read() throws IOException {
if (getLength() == limitBytes) {
return -1;
}
return super.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
len = (int) Math.min(len, limitBytes - getLength());
if (len == 0) {
return -1;
}
return super.read(b, off, len);
}
}
你并不需要关注底层IO流如何实现return -1。实在想看,去看JDK的实现,是c写的。