提示

Java IO ByteArrayOutputStream 使用示例。@ermo

回到上一级

# ByteArrayOutputStream 使用示例

ByteArrayOutputStreamOutputStream 的子类,可以用于输出字节数组。

主要有2个构造方法:

public ByteArrayOutputStream()

public ByteArrayOutputStream(int size)

ByteArrayOutputStream() 可以创建一个字节数组对象,默认容量是 32 个字节。

ByteArrayOutputStream(int size) 同样可以创建一个字节数组对象,容量为 size 个字节。

ByteArrayOutputStream 有以下几个 write() 方法:

方法 描述
public synchronized void write(int b) 将指定的单字节写入输出流
public void write(byte b[]) 将字节数组写入输出流,写入长度为 b.length
public synchronized void write(byte b[], int off, int len) 将字节数组写入输出流,从 b[off] 开始写入,写入长度为 len
public synchronized void writeTo(OutputStream out) 将当前输出流的完整数据写入指定的另一个输出流中

来看一个 ByteArrayOutputStream 的例子:

    /**
     * Write with ByteArrayOutputStream.
     */
    public static void write() {
        String data = "Just made the lemonade.";
        try (ByteArrayOutputStream out = new ByteArrayOutputStream();) {
            byte[] dataBytes = data.getBytes();

            out.write(dataBytes);
            String outData = out.toString();

            System.out.println(outData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * Main method.
     *
     * @param args args
     */
    public static void main(String[] args) {
        writeTo();
    }

输出内容为:

Just made the lemonade.

其他常用方法:

// 返回字节数组
public synchronized byte toByteArray()[]

// 关闭输出流,在 ByteArrayOutputStream 无效
public void close() throws IOException

// 返回当前输出流的数组长度
public synchronized int size()