2021-09-07 IO流(自定义字节流的缓冲区-read和w

2021-09-23  本文已影响0人  Denholm
clipboard.png
clipboard.png
import java.io.*;

public class MyBufferedInputStream {

    private InputStream in;
    private byte[] buf = new byte[1024];
    private int pos = 0, count = 0;

    public MyBufferedInputStream(InputStream in) {
        this.in = in;
    }

    // 一次读一个字节,从缓冲区(字节数组)读取
    public int myRead() throws IOException {
        if (count == 0) {
            // 通过in对象调用硬盘上的数据,并存储到buf中
            count = in.read(buf);
            if (count < 0) {
                return -1;
            }
            pos = 0;
            byte b = buf[pos];

            count--;
            pos++;
            return b & 255;
        } else if (count > 0) {
            byte b = buf[pos];
            count--;
            pos++;
            return b & 0xff;
        }
        return -1;
    }

    public void myClose() throws IOException {
        in.close();
    }

    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 mybis = new MyBufferedInputStream(
                new FileInputStream("E:\\src.png"));
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream("E:\\copy.png"));
        int by;
        while ((by = mybis.myRead()) != -1) {
            bos.write(by);
        }
        mybis.myClose();
        bos.close();
    }

}
上一篇 下一篇

猜你喜欢

热点阅读