先上源码:
/**
* Flushes this output stream and forces any buffered output bytes
* to be written out. The general contract of <code>flush</code> is
* that calling it is an indication that, if any bytes previously
* written have been buffered by the implementation of the output
* stream, such bytes should immediately be written to their
* intended destination.
* <p>
* If the intended destination of this stream is an abstraction provided by
* the underlying operating system, for example a file, then flushing the
* stream guarantees only that bytes previously written to the stream are
* passed to the operating system for writing; it does not guarantee that
* they are actually written to a physical device such as a disk drive.
* <p>
* The <code>flush</code> method of <code>OutputStream</code> does nothing.
*
* @exception IOException if an I/O error occurs.
*/
public void flush() throws IOException {
}
总结有以下几点:
1. flush()下达一条命令给缓冲区,让它将所储存的数据全部清空,即发送给下一级。
2. flush()刷空输出流,并输出所有被缓存的字节。由于某些流支持缓存功能,该方法将把缓存中所有内容强制输出到流中。
3. OutputStream.flush()方法将所有写入到OutputStream的数据冲刷到相应的目标媒介中。比如,如果输出流是FileOutputStream,那么写入到其中的数据可能并没有真正写入到磁盘中。即使所有数据都写入到了FileOutputStream,这些数据还是有可能保留在内存的缓冲区中。通过调用flush()方法,可以把缓冲区内的数据刷新到磁盘(或者网络,以及其他任何形式的目标媒介)中。
例子:
// 模拟浏览器,给tomcat服务端发送符合http协议的请求消息
public static void main(String[] args) throws IOException
{
Socket s = new Socket("127.0.0.1", 80);
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println("GET /myweb/test.jsp HTTP/1.1");
out.println("Accept: */*");
out.println("Accept-Language: zh-CN");
out.println("Accept-Encoding: gzip, deflate");
out.println();
out.flush(); // 清空缓存并输出流
InputStream in = s.getInputStream();
byte b[] = new byte[1024];
int leng = 0;
while((leng = in .read(b)) != -1)
{
String str = new String(b, 0, leng);
System.out.println(str);
}
s.close();
}