-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寫的。