记录一次Socket编程:OutputStream的flush方法
生活随笔
收集整理的這篇文章主要介紹了
记录一次Socket编程:OutputStream的flush方法
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
先上源碼:
/*** 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 {}總結(jié)有以下幾點(diǎn):
1. flush()下達(dá)一條命令給緩沖區(qū),讓它將所儲(chǔ)存的數(shù)據(jù)全部清空,即發(fā)送給下一級(jí)。
2. flush()刷空輸出流,并輸出所有被緩存的字節(jié)。由于某些流支持緩存功能,該方法將把緩存中所有內(nèi)容強(qiáng)制輸出到流中。
3.?OutputStream.flush()方法將所有寫(xiě)入到OutputStream的數(shù)據(jù)沖刷到相應(yīng)的目標(biāo)媒介中。比如,如果輸出流是FileOutputStream,那么寫(xiě)入到其中的數(shù)據(jù)可能并沒(méi)有真正寫(xiě)入到磁盤(pán)中。即使所有數(shù)據(jù)都寫(xiě)入到了FileOutputStream,這些數(shù)據(jù)還是有可能保留在內(nèi)存的緩沖區(qū)中。通過(guò)調(diào)用flush()方法,可以把緩沖區(qū)內(nèi)的數(shù)據(jù)刷新到磁盤(pán)(或者網(wǎng)絡(luò),以及其他任何形式的目標(biāo)媒介)中。
例子:
// 模擬瀏覽器,給tomcat服務(wù)端發(fā)送符合http協(xié)議的請(qǐng)求消息 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(); }?
總結(jié)
以上是生活随笔為你收集整理的记录一次Socket编程:OutputStream的flush方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 面试中,答不出产品方法论?4个方法教给你
- 下一篇: Mysql:Sql的执行顺序