private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//为什么-8?Integer的MAX_VALUE在32位系统中位2^15-1,在64位系统中位2^31-1
package ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
/**
* 字符缓冲流
* @author Administrator
*
*/
public class MyByteArrayOutputStream extends OutputStream{
public byte buf[];//字节缓冲区
public int count;//写入的字节数
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//为什么-8?Integer的MAX_VALUE在32位系统中位2^15-1,在64位系统中位2^31-1
public MyByteArrayOutputStream() {
this(32);//初始值为啥是32
}
public MyByteArrayOutputStream(int size){
if(size < 0){
throw new IllegalArgumentException("错误的初始化大小" + size);
}
buf = new byte[size];
}
private void ensureCapacity(int minCapacity){
if(minCapacity - buf.length > 0){//r如果将要添加的值超过了byte的数组的长度将原数组增长
grow(minCapacity);
}
}
private void grow(int minCapacity){//2^30+1 2^31
int oldCapacity = buf.length;//2^30 2^31-1
int newCapacity = oldCapacity << 1;//容量增长为原来的两倍2^31
if(newCapacity - minCapacity < 0){
newCapacity = minCapacity;//新增长的容量小于添加后的实际容量,将容量增长为实际容量
}
if(newCapacity - MAX_ARRAY_SIZE > 0){//新增长的容量大于最大容量
newCapacity = hugeCapacity(minCapacity);
}
System.out.println(newCapacity);
buf = Arrays.copyOf(buf,newCapacity);//将数组的内容考到新的数组中
}
private static int hugeCapacity(int minCapacity){
if(minCapacity < 0){
throw new OutOfMemoryError();//内存溢出,为什么要抛出内存溢出
}
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;//设置数组的最大容量为Integer.MAX_VAL
}
public synchronized void write(int b){
ensureCapacity(count + 1);
buf[count] = (byte)b;
count +=1;
}
public synchronized void write(byte b [],int off,int len){
if((off < 0) || (off > b.length) || (len < 0) || ((off + len ) - b.length > 0)){
throw new IndexOutOfBoundsException();
}
ensureCapacity(count + len);
System.arraycopy(b, off, buf, count, len);
count +=len;
}
public synchronized void writeTo(OutputStream out)throws IOException{
out.write(buf, 0, count);
}
public synchronized void reset(){
count = 0;
}
public synchronized byte toByteArray()[]{
return Arrays.copyOf(buf, count);
}
public synchronized int size(){
return count;
}
public synchronized String toString(){
return new String(buf,0,count);
}
public synchronized String toString(String charsetName) throws UnsupportedEncodingException{
return new String(buf,0,count,charsetName);
}
@Deprecated
public synchronized String toString(int hibyte){
return new String(buf,hibyte,0,count);
}
public void close() throws IOException{}
}