Java中的ByteArrayOutputStream类

x33g5p2x  于2022-10-06 转载在 Java  
字(2.0k)|赞(0)|评价(0)|浏览(290)

ByteArrayOutputStream是一个输出流的实现,它使用一个字节数组作为目标。

ByteArrayOutputStream构造函数

* ByteArrayOutputStream() - 创建一个新的字节数组输出流。

  • ByteArrayOutputStream(int size) - 创建一个新的字节数组输出流,其缓冲区容量为指定的字节数。
    在构造函数的第一种形式中,创建一个32字节的缓冲区。在第二种形式中,创建的缓冲区的大小等于numBytes所指定的大小。

当数据被写入缓冲区时,缓冲区会自动增长。可以使用toByteArray()和toString()检索数据。
关闭一个
ByteArrayOutputStream
没有任何效果。这个类中的方法可以在流被关闭后被调用而不产生IOException

ByteArrayOutputStream方法

void close() - 关闭一个ByteArrayOutputStream没有任何效果。
void reset() - 将这个字节数组输出流的计数字段重置为零,这样输出流中所有当前累积的输出都被丢弃了。
int size() - 返回缓冲区的当前大小。
byte[] toByteArray() - 创建一个新分配的字节数组。
String toString() - 使用平台的默认字符集将缓冲区的内容转换为解码字节的字符串。
String toString(String charsetName) - 通过使用指定的字符集对字节进行解码,将缓冲区的内容转换为一个字符串。
void write(byte[] b, int off, int len) - 从指定的字节数组中从偏移量off开始向这个字节数组输出流写入len字节。
void write(int b) - 将指定的字节写到这个字节数组的输出流中。
void writeTo(OutputStream out) - 将这个字节数组输出流的全部内容写到指定的输出流参数中,就像使用out.write(buf, 0, count)调用输出流的写法一样。

ByteArrayOutputStream例子

让我们写一个例子来演示ByteArrayOutputStream类的用法。这个程序使用了try-with-resources。它需要JDK 7或更高版本。

import java.io.*;
class ByteArrayOutputStreamDemo {
    public static void main(String args[]) {
        ByteArrayOutputStream f = new ByteArrayOutputStream();
        String s = "This should end up in the array";
        byte buf[] = s.getBytes();
        try {
            f.write(buf);
        } catch (IOException e) {
            System.out.println("Error Writing to Buffer");
            return;
        }
        System.out.println("Buffer as a string");
        System.out.println(f.toString());
        System.out.println("Into array");
        byte b[] = f.toByteArray();
        for (int i = 0; i < b.length; i++) System.out.print((char) b[i]);
        System.out.println("\nTo an OutputStream()");
        // Use try-with-resources to manage the file stream.
        try (FileOutputStream f2 = new FileOutputStream("test.txt")) {
            f.writeTo(f2);
        } catch (IOException e) {
            System.out.println("I/O Error: " + e);
            return;
        }

        System.out.println("Doing a reset");
        f.reset();
        for (int i = 0; i\ < 3; i++) f.write('X');
        System.out.println(f.toString());
    }
}

当你运行该程序时,你会看到以下输出。注意在调用reset( )后,三个X在开始时就结束了.

Buffer as a string
This should end up in the array
Into array
This should end up in the array
To an OutputStream()
Doing a reset
XXX

相关文章

微信公众号

最新文章

更多