为什么可以从已经关闭的 ByteArrayOutputStream 中读取数据?
Why you can read data from already closed ByteArrayOutputStream?
我想知道为什么您仍然可以从已经关闭的 ByteArrayOutputStream
中读取字节。文档中的这一行不是相反的意思吗?
public void close ()
: Closes this stream. This releases system resources used for this stream.
示例代码:
String data = "Some string ...";
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(bOut);
dOut.write(data.getBytes());
dOut.close();
System.out.println("Length: " + bOut.toByteArray().length);
System.out.println("Byte #2: " + bOut.toByteArray()[2]);
输出:
Length: 15
Byte #2: 109
我是不是做错了什么?
ByteArrayOutputStream.toByteArray 只是复制缓冲区中的内容;它不再从流中读取任何内容。
public synchronized byte[] toByteArray() {
return Arrays.copyOf(buf, count);
}
还有这个class有点特别。参见 Java documentation 和代码。
Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.
public void close() throws IOException {
}
close()
什么都没做。
我想知道为什么您仍然可以从已经关闭的 ByteArrayOutputStream
中读取字节。文档中的这一行不是相反的意思吗?
public void close ()
: Closes this stream. This releases system resources used for this stream.
示例代码:
String data = "Some string ...";
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
DataOutputStream dOut = new DataOutputStream(bOut);
dOut.write(data.getBytes());
dOut.close();
System.out.println("Length: " + bOut.toByteArray().length);
System.out.println("Byte #2: " + bOut.toByteArray()[2]);
输出:
Length: 15
Byte #2: 109
我是不是做错了什么?
ByteArrayOutputStream.toByteArray 只是复制缓冲区中的内容;它不再从流中读取任何内容。
public synchronized byte[] toByteArray() {
return Arrays.copyOf(buf, count);
}
还有这个class有点特别。参见 Java documentation 和代码。
Closing a ByteArrayOutputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.
public void close() throws IOException {
}
close()
什么都没做。