资讯专栏INFORMATION COLUMN

java 字节流源码解析

geekidentity / 1385人阅读

摘要:重要方法一个一个字节读取,放到数组中重要方法读取一个字节调用方法读取的内容调用方法声明继承自构造方法从中读取一个字节归根究底,目的是将数据放入中缓存,下次读取可以直接获取重要方法调用模板方法,由子类实现写一

1. InputStream

重要方法:

</>复制代码

  1. public int read(byte b[], int off, int len) throws IOException {
  2. if (b == null) {
  3. throw new NullPointerException();
  4. } else if (off < 0 || len < 0 || len > b.length - off) {
  5. throw new IndexOutOfBoundsException();
  6. } else if (len == 0) {
  7. return 0;
  8. }
  9. int c = read();
  10. if (c == -1) {
  11. return -1;
  12. }
  13. b[off] = (byte)c;
  14. int i = 1;
  15. try {
  16. for (; i < len ; i++) {
  17. c = read();
  18. if (c == -1) {
  19. break;
  20. }
  21. b[off + i] = (byte)c;
  22. }
  23. } catch (IOException ee) {
  24. }
  25. return i;
  26. }

一个一个字节读取,放到byte数组中

1.1 FileInputStream

重要方法:

</>复制代码

  1. // 读取一个字节
  2. public int read() throws IOException {
  3. return read0();
  4. }
  5. // 调用 native 方法
  6. private native int read0() throws IOException;

</>复制代码

  1. // 读取b.length的内容
  2. public int read(byte b[]) throws IOException {
  3. return readBytes(b, 0, b.length);
  4. }
  5. public int read(byte b[], int off, int len) throws IOException {
  6. return readBytes(b, off, len);
  7. }
  8. // 调用 native 方法
  9. private native int readBytes(byte b[], int off, int len) throws IOException;
1.2 BufferedInputStream 1.2.1 声明

</>复制代码

  1. // 继承自 FilterInputStream
  2. public class BufferedInputStream extends FilterInputStream
1.2.2 构造方法

</>复制代码

  1. private static int DEFAULT_BUFFER_SIZE = 8192;
  2. public BufferedInputStream(InputStream in) {
  3. this(in, DEFAULT_BUFFER_SIZE);
  4. }
  5. public BufferedInputStream(InputStream in, int size) {
  6. super(in);
  7. if (size <= 0) {
  8. throw new IllegalArgumentException("Buffer size <= 0");
  9. }
  10. buf = new byte[size];
  11. }
  12. // super(in);
  13. protected FilterInputStream(InputStream in) {
  14. this.in = in;
  15. }
1.2.3 read

</>复制代码

  1. public synchronized int read() throws IOException {
  2. if (pos >= count) {
  3. fill();
  4. if (pos >= count)
  5. return -1;
  6. }
  7. // 从buf中读取一个字节
  8. return getBufIfOpen()[pos++] & 0xff;
  9. }
  10. private byte[] getBufIfOpen() throws IOException {
  11. byte[] buffer = buf;
  12. if (buffer == null)
  13. throw new IOException("Stream closed");
  14. return buffer;
  15. }

</>复制代码

  1. public synchronized int read(byte b[], int off, int len) throws IOException{
  2. getBufIfOpen(); // Check for closed stream
  3. if ((off | len | (off + len) | (b.length - (off + len))) < 0) {
  4. throw new IndexOutOfBoundsException();
  5. } else if (len == 0) {
  6. return 0;
  7. }
  8. int n = 0;
  9. for (;;) {
  10. int nread = read1(b, off + n, len - n);
  11. if (nread <= 0)
  12. return (n == 0) ? nread : n;
  13. n += nread;
  14. if (n >= len)
  15. return n;
  16. // if not closed but no bytes available, return
  17. InputStream input = in;
  18. if (input != null && input.available() <= 0)
  19. return n;
  20. }
  21. }
  22. private int read1(byte[] b, int off, int len) throws IOException {
  23. int avail = count - pos;
  24. if (avail <= 0) {
  25. /* If the requested length is at least as large as the buffer, and
  26. if there is no mark/reset activity, do not bother to copy the
  27. bytes into the local buffer. In this way buffered streams will
  28. cascade harmlessly. */
  29. if (len >= getBufIfOpen().length && markpos < 0) {
  30. return getInIfOpen().read(b, off, len);
  31. }
  32. fill();
  33. avail = count - pos;
  34. if (avail <= 0) return -1;
  35. }
  36. int cnt = (avail < len) ? avail : len;
  37. System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
  38. pos += cnt;
  39. return cnt;
  40. }
  41. // 归根究底,目的是将数据放入buffer中缓存,下次读取可以直接获取
  42. private void fill() throws IOException {
  43. byte[] buffer = getBufIfOpen();
  44. if (markpos < 0)
  45. pos = 0; /* no mark: throw away the buffer */
  46. else if (pos >= buffer.length) /* no room left in buffer */
  47. if (markpos > 0) { /* can throw away early part of the buffer */
  48. int sz = pos - markpos;
  49. System.arraycopy(buffer, markpos, buffer, 0, sz);
  50. pos = sz;
  51. markpos = 0;
  52. } else if (buffer.length >= marklimit) {
  53. markpos = -1; /* buffer got too big, invalidate mark */
  54. pos = 0; /* drop buffer contents */
  55. } else if (buffer.length >= MAX_BUFFER_SIZE) {
  56. throw new OutOfMemoryError("Required array size too large");
  57. } else { /* grow buffer */
  58. int nsz = (pos <= MAX_BUFFER_SIZE - pos) ?
  59. pos * 2 : MAX_BUFFER_SIZE;
  60. if (nsz > marklimit)
  61. nsz = marklimit;
  62. byte nbuf[] = new byte[nsz];
  63. System.arraycopy(buffer, 0, nbuf, 0, pos);
  64. if (!bufUpdater.compareAndSet(this, buffer, nbuf)) {
  65. // Can"t replace buf if there was an async close.
  66. // Note: This would need to be changed if fill()
  67. // is ever made accessible to multiple threads.
  68. // But for now, the only way CAS can fail is via close.
  69. // assert buf == null;
  70. throw new IOException("Stream closed");
  71. }
  72. buffer = nbuf;
  73. }
  74. count = pos;
  75. int n = getInIfOpen().read(buffer, pos, buffer.length - pos);
  76. if (n > 0)
  77. count = n + pos;
  78. }

</>复制代码

  1. private int read1(byte[] b, int off, int len) throws IOException {
  2. int avail = count - pos;
  3. if (avail <= 0) {
  4. /* If the requested length is at least as large as the buffer, and
  5. if there is no mark/reset activity, do not bother to copy the
  6. bytes into the local buffer. In this way buffered streams will
  7. cascade harmlessly. */
  8. if (len >= getBufIfOpen().length && markpos < 0) {
  9. return getInIfOpen().read(b, off, len);
  10. }
  11. fill();
  12. avail = count - pos;
  13. if (avail <= 0) return -1;
  14. }
  15. int cnt = (avail < len) ? avail : len;
  16. System.arraycopy(getBufIfOpen(), pos, b, off, cnt);
  17. pos += cnt;
  18. return cnt;
  19. }
2. OutputStream

重要方法:

</>复制代码

  1. public void write(byte b[], int off, int len) throws IOException {
  2. if (b == null) {
  3. throw new NullPointerException();
  4. } else if ((off < 0) || (off > b.length) || (len < 0) ||
  5. ((off + len) > b.length) || ((off + len) < 0)) {
  6. throw new IndexOutOfBoundsException();
  7. } else if (len == 0) {
  8. return;
  9. }
  10. for (int i = 0 ; i < len ; i++) {
  11. // 调用模板方法,由子类实现
  12. write(b[off + i]);
  13. }
  14. }
2.1 FileOutputStream 2.1.1 write

</>复制代码

  1. // 写一个字节
  2. public void write(int b) throws IOException {
  3. write(b, append);
  4. }
  5. private native void write(int b, boolean append) throws IOException;

</>复制代码

  1. public void write(byte b[]) throws IOException {
  2. writeBytes(b, 0, b.length, append);
  3. }
  4. private native void writeBytes(byte b[], int off, int len, boolean append)
  5. throws IOException;

</>复制代码

  1. public void write(byte b[], int off, int len) throws IOException {
  2. writeBytes(b, off, len, append);
  3. }
2.2 BuffedOutputStream 2.2.1 声明

</>复制代码

  1. public class BufferedOutputStream extends FilterOutputStream
2.2.2 constructor

</>复制代码

  1. // 在内存中申请一个 byte[]
  2. public BufferedOutputStream(OutputStream out) {
  3. this(out, 8192);
  4. }
  5. public BufferedOutputStream(OutputStream out, int size) {
  6. super(out);
  7. if (size <= 0) {
  8. throw new IllegalArgumentException("Buffer size <= 0");
  9. }
  10. buf = new byte[size];
  11. }
2.2.3 write

</>复制代码

  1. // 写一个字节
  2. public synchronized void write(int b) throws IOException {
  3. if (count >= buf.length) {
  4. flushBuffer();
  5. }
  6. buf[count++] = (byte)b;
  7. }
  8. // 调用 outputstream 的 write方法
  9. private void flushBuffer() throws IOException {
  10. if (count > 0) {
  11. out.write(buf, 0, count);
  12. count = 0;
  13. }
  14. }

</>复制代码

  1. public synchronized void write(byte b[], int off, int len) throws IOException {
  2. if (len >= buf.length) {
  3. /* If the request length exceeds the size of the output buffer,
  4. flush the output buffer and then write the data directly.
  5. In this way buffered streams will cascade harmlessly. */
  6. flushBuffer();
  7. out.write(b, off, len);
  8. return;
  9. }
  10. if (len > buf.length - count) {
  11. flushBuffer();
  12. }
  13. // 首先存放到buffer内存中
  14. System.arraycopy(b, off, buf, count, len);
  15. count += len;
  16. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72254.html

相关文章

  • Java开发

    摘要:大多数待遇丰厚的开发职位都要求开发者精通多线程技术并且有丰富的程序开发调试优化经验,所以线程相关的问题在面试中经常会被提到。将对象编码为字节流称之为序列化,反之将字节流重建成对象称之为反序列化。 JVM 内存溢出实例 - 实战 JVM(二) 介绍 JVM 内存溢出产生情况分析 Java - 注解详解 详细介绍 Java 注解的使用,有利于学习编译时注解 Java 程序员快速上手 Kot...

    LuDongWei 评论0 收藏0
  • JVM实战---类加载的过程

    任何程序都需要加载到内存才能与CPU进行交流 同理, 字节码.class文件同样需要加载到内存中,才可以实例化类 ClassLoader的使命就是提前加载.class 类文件到内存中 在加载类时,使用的是Parents Delegation Model(溯源委派加载模型) Java的类加载器是一个运行时核心基础设施模块,主要是在启动之初进行类的加载、链接、初始化 showImg(https://s...

    bladefury 评论0 收藏0
  • Okio 源码解析(一):数据读取流程

    摘要:封装了和,并且有多个优点提供超时机制不需要人工区分字节流与字符流,易于使用易于测试本文先介绍的基本用法,然后分析源码中数据读取的流程。和分别用于提供字节流和接收字节流,对应于和。和则是保存了相应的缓存数据用于高效读写。 简介 Okio 是 square 开发的一个 Java I/O 库,并且也是 OkHttp 内部使用的一个组件。Okio 封装了 java.io 和 java.nio,...

    senntyou 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<