这取决于您使用的 OutputStream 类型。
让我们从基础开始,通过分析 OutputStream 的刷新作为合约提出的内容:
公共无效冲洗()
抛出 IOException
刷新此输出流并强制任何缓冲的输出字节
写出来。 flush 的一般约定是调用它是
指示,如果 任何先前写入的字节已被
输出流的实现,这样的字节应该立即
写到他们的预定目的地。
如果此流的预期目的地是提供的抽象
由底层操作系统,例如一个文件,然后刷新
流仅保证以前写入流的 字节
传递给操作系统写入;它不保证
它们实际上被写入物理设备,例如磁盘
开车。
OutputStream的flush方法什么都不做。
如果你看到 OutputStream 的 flush 方法,它实际上什么都不做:
public void flush() throws IOException {
}
这个想法是,装饰 OutputStream 的实现必须处理它的刷新,然后将其级联到其他 OutputStream 直到它到达操作系统,如果是这样的话。
所以它做了一些事情!通过执行它的任何人。具体类将覆盖刷新以执行诸如将数据移动到磁盘或通过网络发送数据(您的情况)。
如果您检查 BufferedOutputStream 的刷新:
/**
* Flushes this buffered output stream. This forces any buffered
* output bytes to be written out to the underlying output stream.
*
* @exception IOException if an I/O error occurs.
* @see java.io.FilterOutputStream#out
*/
public synchronized void flush() throws IOException {
flushBuffer();
out.flush();
}
/** Flush the internal buffer */
private void flushBuffer() throws IOException {
if (count > 0) {
out.write(buf, 0, count);
count = 0;
}
}
您可能会看到它正在将自己缓冲区的内容写入包装的 OutputStream。你可以看到它的缓冲区的默认大小(或者你可以改变它),看看它的构造函数:
/**
* The internal buffer where data is stored.
*/
protected byte buf[];
/**
* Creates a new buffered output stream to write data to the
* specified underlying output stream.
*
* @param out the underlying output stream.
*/
public BufferedOutputStream(OutputStream out) {
this(out, 8192);
}
/**
* Creates a new buffered output stream to write data to the
* specified underlying output stream with the specified buffer
* size.
*
* @param out the underlying output stream.
* @param size the buffer size.
* @exception IllegalArgumentException if size <= 0.
*/
public BufferedOutputStream(OutputStream out, int size) {
super(out);
if (size <= 0) {
throw new IllegalArgumentException("Buffer size <= 0");
}
buf = new byte[size];
}
因此,BufferedInputStream 缓冲区的默认大小为 8192 字节。
既然您已经掌握了要点,请查看 HttpURLConnection 中为您使用的代码 OutputStream 以熟悉其缓冲区(如果有)。
在您的 Java 之旅中,您最终可能会得到一些将刷新操作委托给操作系统的本机代码。在这种情况下,您可能必须检查您的操作系统是否正在使用某些缓冲区以及在处理 IO 时它的大小是多少。我知道这部分答案可能听起来很宽泛,但事实就是如此。您需要知道您正在使用什么,才能了解其背后的原因。
看看这个问题:
What is the purpose of flush() in Java streams?
还有这篇文章:
http://www.oracle.com/technetwork/articles/javase/perftuning-137844.html
干杯!