美文网首页
2021-09-07 IO流(自定义字节流的缓冲区-read和w

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

作者: Denholm | 来源:发表于2021-09-23 20:48 被阅读0次
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();
    }

}

相关文章

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

  • IO流——字节流4种copy方式

    JAVA基本IO流框架 字节流整体可分为带缓冲区的流和不带缓冲区的流可分为逐字节复制的流和逐块复制的流(块其实就是...

  • 字节流和字符流的区别&常用方法总结

    参考:深入理解Java中的IO · 节流没有缓冲区,是直接输出的,而字符流是输出到缓冲区的。因此在输出时,字...

  • Java NIO

    NIO和传统IO区别 传统IO是面向流的(字节流或字符流),NIO是面向缓冲区的。面向流意味着每次从流中读取n个字...

  • IO流简介

    io流的作用:读写设备上的数据,硬盘文件、内存、键盘、网络.... io流分类:输入流和输出流,字节流和字符流 字...

  • 字符流缓冲区

    字符流缓冲区和字节流缓冲区底层运行差异不大

  • IO流 2018-05-07

    字节流和字符流: 1字节流(均为抽象类):在字节流中定义了方法read(),用于从字节流中读取对象: public...

  • IO流

    IO流 Input:输入流,用于读取数据 Output:输出流,用于写数据 IO分类 字节流 字节流就是读和取都是...

  • NIO

    传统IO和普通IO的区别 传统IO:面向流,阻塞IO(Blocking), selector NIO:面向缓冲区,...

  • Java 中 IO 流分为几种?BIO,NIO,AIO 有什么区

    java 中 IO 流分为几种? 按照流的流向分,可以分为输入流和输出流; 按照操作单元划分,可以划分为字节流和字...

网友评论

      本文标题:2021-09-07 IO流(自定义字节流的缓冲区-read和w

      本文链接:https://www.haomeiwen.com/subject/wbnpwltx.html