java io学习(二)ByteArrayOutputStream的简介,源码分析和示例2014-08-12ByteArrayOutputStream的简介,源码分析和示例(包括OutputStream)前面学习ByteArrayInputStream,了解了“输入流”。接下来,我们学习与ByteArrayInputStream相对应的输出流,即ByteArrayOutputStream。本章,我们会先对ByteArrayOutputStream进行介绍,在了解了它的源码之后,再通过示例来掌握如何使用它。ByteArrayOutputStream 介绍ByteArrayOutputStream 是字节数组输出流。它继承于OutputStream。ByteArrayOutputStream 中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray() 和 toString() 获取数据。 OutputStream 函数列表我们来看看ByteArrayOutputStream的父类OutputStream的函数接口。
// 构造函数OutputStream()voidclose() voidflush() voidwrite(byte[] buffer, int offset, int count) voidwrite(byte[] buffer)abstract voidwrite(int oneByte)
ByteArrayOutputStream 函数列表
// 构造函数ByteArrayOutputStream()ByteArrayOutputStream(int size)voidclose()synchronized voidreset() int size()synchronized byte[]toByteArray() StringtoString(int hibyte) StringtoString(String charsetName) StringtoString()synchronized voidwrite(byte[] buffer, int offset, int len)synchronized voidwrite(int oneByte)synchronized voidwriteTo(OutputStream out)
OutputStream和ByteArrayOutputStream源码分析OutputStream是ByteArrayOutputStream的父类,我们先看看OutputStream的源码,然后再学ByteArrayOutputStream的源码。1. OutputStream.java源码分析(基于jdk1.7.40)
package java.io; public abstract class OutputStream implements Closeable, Flushable {// 将字节b写入到“输出流”中。// 它在子类中实现!public abstract void write(int b) throws IOException; // 写入字节数组b到“字节数组输出流”中。public void write(byte b[]) throws IOException {write(b, 0, b.length);} // 写入字节数组b到“字节数组输出流”中,并且off是“数组b的起始位置”,len是写入的长度public void write(byte b[], int off, int len) throws IOException {if (b == null) {throw new NullPointerException();} else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {throw new IndexOutOfBoundsException();} else if (len == 0) {return;}for (int i = 0 ; i < len ; i++) {write(b[off + i]);}} public void flush() throws IOException {} public void close() throws IOException {}}