📜  Java I/O-ByteArrayOutputStream

📅  最后修改于: 2020-09-27 02:18:38             🧑  作者: Mango

Java ByteArrayOutputStream类

Java ByteArrayOutputStream类用于将公共数据写入多个文件。在此流中,数据被写入一个字节数组,该字节数组以后可以写入多个流。

ByteArrayOutputStream保存数据的副本,并将其转发到多个流。

ByteArrayOutputStream的缓冲区根据数据自动增长。

Java ByteArrayOutputStream类声明

让我们看一下Java.io.ByteArrayOutputStream类的声明:

public class ByteArrayOutputStream extends OutputStream

Java ByteArrayOutputStream类构造函数

Constructor Description
ByteArrayOutputStream() Creates a new byte array output stream with the initial capacity of 32 bytes, though its size increases if necessary.
ByteArrayOutputStream(int size) Creates a new byte array output stream, with a buffer capacity of the specified size, in bytes.

Java ByteArrayOutputStream类方法

Method Description
int size() It is used to returns the current size of a buffer.
byte[] toByteArray() It is used to create a newly allocated byte array.
String toString() It is used for converting the content into a string decoding bytes using a platform default character set.
String toString(String charsetName) It is used for converting the content into a string decoding bytes using a specified charsetName.
void write(int b) It is used for writing the byte specified to the byte array output stream.
void write(byte[] b, int off, int len It is used for writing len bytes from specified byte array starting from the offset off to the byte array output stream.
void writeTo(OutputStream out) It is used for writing the complete content of a byte array output stream to the specified output stream.
void reset() It is used to reset the count field of a byte array output stream to zero value.
void close() It is used to close the ByteArrayOutputStream.

Java ByteArrayOutputStream的示例

让我们看一下一个Java ByteArrayOutputStream类的简单示例,该类将公共数据写入2个文件:f1.txt和f2.txt。

package com.javatpoint;
import java.io.*;
public class DataStreamExample {
public static void main(String args[])throws Exception{  
  FileOutputStream fout1=new FileOutputStream("D:\\f1.txt");  
  FileOutputStream fout2=new FileOutputStream("D:\\f2.txt");  
  
  ByteArrayOutputStream bout=new ByteArrayOutputStream();  
  bout.write(65);  
  bout.writeTo(fout1);  
  bout.writeTo(fout2);  
  
  bout.flush();  
  bout.close();//has no effect  
  System.out.println("Success...");  
 }  
} 

输出:

Success...

f1.txt:

A

f2.txt:

A