java.io
包中的ByteArrayOutputStream
类可用于将输出数据(以字节为单位)写入数组。
它扩展了OutputStream
抽象类。
注意:ByteArrayOutputStream
维护一个内部字节数组来存储数据。
创建ByteArrayOutputStream
为了创建字节数组输出流,我们必须首先导入java.io.ByteArrayOutputStream
包。导入包后,我们可以这样创建输出流。
// Creates a ByteArrayOutputStream with default size
ByteArrayOutputStream out = new ByteArrayOutputStream();
这里,我们创建了一个输出流,它会将数据写入一个默认大小为32字节的字节数组。但是,我们可以更改数组的默认大小。
// Creating a ByteArrayOutputStream with specified size
ByteArrayOutputStream out = new ByteArrayOutputStream(int size);
在此,size 指定数组的长度。
ByteArrayOutputStream的方法
ByteArrayOutputStream
类提供了OutputStream
类中存在的方法的实现。
write() 方法
write(int byte)
- 将指定的字节写入输出流write(byte[] array)
- 将指定数组中的字节写入输出流write(byte[] arr, int start, int length)
- 将等于length的字节数从指定位置start开始的数组写入输出流writeTo(ByteArrayOutputStream out1)
- 将当前输出流的全部数据写入指定的输出流
示例:使用ByteArrayOutputStream写入数据
import java.io.ByteArrayOutputStream;
class Main {
public static void main(String[] args) {
String data = "This is a line of text inside the string.";
try {
// Creates an output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] array = data.getBytes();
// Writes data to the output stream
out.write(array);
// Retrieves data from the output stream in string format
String streamData = out.toString();
System.out.println("Output stream: " + streamData);
out.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
输出
Output stream: This is a line of text inside the string.
在上面的示例中,我们创建了一个名为output的字节数组输出流。
ByteArrayOutputStream output = new ByteArrayOutputStream();
为了将数据写入输出流,我们使用了write()
方法。
注意:程序中使用的getBytes()方法将字符串转换为字节数组。
从ByteArrayOutputStream访问数据
toByteArray()
- 返回输出流中的数组toString()
- 以字符串形式返回输出流的全部数据
例如,
import java.io.ByteArrayOutputStream;
class Main {
public static void main(String[] args) {
String data = "This is data.";
try {
// Creates an output stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
// Writes data to the output stream
out.write(data.getBytes());
// Returns an array of bytes
byte[] byteData = out.toByteArray();
System.out.print("Data using toByteArray(): ");
for(int i=0; i<byteData.length; i++) {
System.out.print((char)byteData[i]);
}
// Returns a string
String stringData = out.toString();
System.out.println("\nData using toString(): " + stringData);
out.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
输出
Data using toByteArray(): This is data. Data using toString(): This is data.
在上面的示例中,我们创建了一个字节数组来存储toByteArray()
方法返回的数据。
然后,我们使用for循环访问数组中的每个字节。这里,每个字节都通过类型转换转换为相应的字符。
close() 方法
要关闭输出流,我们可以使用close()
方法。
然而,close()
方法在ByteArrayOutputStream
类中没有效果。即使调用了close()
方法,我们也可以使用此类的方法。
ByteArrayOutputStream的其他方法
方法 | 描述 |
---|---|
size() |
返回输出流中数组的大小 |
flush() |
清空输出流 |
要了解更多,请访问Java ByteArrayOutputStream (官方Java文档)。