读书人

自个儿实现BufferedInputStream

发布时间: 2013-10-01 12:15:56 作者: rapoo

自己实现BufferedInputStream

package test;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;class MyBufferedInputStream{private InputStream in;private byte buf [] = new byte[1000];private int pos = 0;private int count = 0;MyBufferedInputStream(InputStream in){this.in = in;}public int myRead()throws IOException{if(count == 0){count = in.read(buf);if(count < 0)return -1;pos = 0;byte b = buf[pos];count--;pos++;return b & 0xff;}else if(count > 0){byte b = buf[pos];count--;pos++;return b & 0xff; /*由于b是byte类型,返回时Java会自动提升至int,所以为了确保不返回-1,将b与0xff与运算。 即读取到b为-1时,2进制表示为11111111 byte——》int   11111111——》11111111 11111111 11111111 11111111 与0xff做与运算 ——》00000000 00000000 00000000 11111111 */}elsereturn -1;}public void myClose()throws IOException{in.close();}}public class MyBufferedInputStreamDemo{public static void main(String args[])throws IOException{long start = System.currentTimeMillis();copy();long end = System.currentTimeMillis();System.out.println((end - start) + "毫秒");}public static void copy()throws IOException{MyBufferedInputStream bufis = new MyBufferedInputStream(new FileInputStream("D:\\My Documents\\My Pictures\\未命名.jpg"));BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("D:\\My Documents\\My Pictures\\test.jpg"));int by = 0;while((by = bufis.myRead()) != -1){bufos.write(by);//byte强制转换int 去掉之前做与运算产生的多与的3个8位。}bufos.close();bufis.myClose();}}


读书人网 >编程

热点推荐