Java設計Io流可謂是煞費苦心,如果你是初學者我敢保證第一次接觸Java的IO類,一定會“狂暈!!”,暈,倒不是因爲它有多麼難學,而是太多,而且及其讓人容易迷惑。在編程日子中,尤其是在網絡編程中,幾乎離不開Java的IO,關於Java的IO流的分類,可以到網上soso,今天跟大家分享一下flush方法。
1. OutputStream類的flush方法
該類實現了Flushable接口,所以重寫了flush方法,看看flush()源碼,會更加的讓你明白:
- public void flush() throws IOException {
- }
sorry,該實現爲空。就是一個空方法,什麼也不做。看清楚啊,該方法不是抽象方法,是一個實實在在的方法。除了方法體中一無所有,其它還好!!!汗!!!看JDK的api如何解釋!
- flush
- public void flush()
- throws IOException
- 刷新此輸出流並強制寫出所有緩衝的輸出字節。flush 的常規協定是:如果此輸出流的實現已經緩衝了以前寫入的任何字節,則調用此方法指示應將這些字節立即寫入它們預期的目標。
- 如果此流的預期目標是由基礎操作系統提供的一個抽象(如一個文件),則刷新此流只能保證將以前寫入到流的字節傳遞給操作系統進行寫入,但不保證能將這些字節實際寫入到物理設備(如磁盤驅動器)。
- OutputStream 的 flush 方法不執行任何操作。
- 指定者:
- 接口 Flushable 中的 flush
- 拋出:
- IOException - 如果發生 I/O 錯誤。
開始,我安慰自己,該類是一個抽象類,它的子類肯定重寫了該方法。好吧,OutputStream的直接子類有:
- ByteArrayOutputStream
- FileOutputStream
- FilterOutputStream
- ObjectOutputStream
- OutputStream
- PipedOutputStream
注意:這裏的子類OutputStream是包 org.omg.CORBA.portable 的。
對於FileOutputStream、ByteArrayOutputStream、org.omg.CORBA.portable.OutputStream類它們的flush()方法均是從父類繼承的flush方法。
FilterOutputStream類重寫了flush()方法,但是實質還是調用父類的flush方法。
ObjectOutputStream、PipedOutputStream類重寫了flush()方法。
好吧,來兩個個小例子,很簡單,第一個例子主要是向文本中寫入字符串,第二個例子向文本中寫入一定字節的數據,如下代碼:
- package mark.zhang;
- import java.io.BufferedOutputStream;
- import java.io.DataOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- public class Test {
- public static void main(String[] args) throws Exception {
- File file = new File("text.txt");
- if(!file.exists()) {
- file.createNewFile();
- }
- FileOutputStream fos = new FileOutputStream(file);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- DataOutputStream dos = new DataOutputStream(fos);
- dos.writeBytes("java io");
- }
- }
- package mark.zhang;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- public class Test {
- public static void main(String[] args) throws Exception {
- File file = new File("text.txt");
- if(!file.exists()) {
- file.createNewFile();
- }
- FileOutputStream fos = new FileOutputStream(file);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- byte[] b = new byte[1024*8];
- bos.write(b);
- bos.flush();
- }
- }
這兩段代執行後,分別會在當前目錄下產生7字節的文件(內容爲java io)和1KB字節的文件。說到這裏,有些人會說,這有什麼稀奇,至於嗎???呵呵,別急,淡定!!現在修改第二個代碼,主要是註釋掉調用flush()方法,如下:
- package mark.zhang;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- public class Test {
- public static void main(String[] args) throws Exception {
- File file = new File("text.txt");
- if(!file.exists()) {
- file.createNewFile();
- }
- FileOutputStream fos = new FileOutputStream(file);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- byte[] b = new byte[1024];
- bos.write(b);
- //bos.flush();
- }
- }
ok,再次運行代碼,額的神啊???文件大小居然是o字節。why????flush()方法有那麼神奇,汗??!!!
仔細的你會發現,第一個代碼並沒有調用flush()方法,居然可以。爲什麼第二個就不可以呢?還是看源碼,有說服力。
DataOutputStream繼承FilterOutputStream,實現了DataOutput接口。我們知道FilterOutputStream類重寫了flush()方法,但是實質還是調用父類的flush方法。DataOutputStream類的flush()方法效仿其父類FilterOutputStream的做法,如下:
- public void flush() throws IOException {
- out.flush();
- }
那麼,即使你在代碼後面加上dos.flush();與不加是一樣的效果,因爲它們的父類flush()方法均爲空,這就是爲什麼第一個代碼的神奇所在。再看看第二個代碼的病因在哪裏?先看看BufferedOutputStream類的結構:
- public class BufferedOutputStream extends FilterOutputStream
再看看,它的flush()方法:
- 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;
- }
- }
不錯,該類重寫了flush()方法,不像前面幾個那樣不是繼承就是山寨父類的flush()方法。BufferedOutputStream 類是一個使用了緩衝技術的類。這種類一把都會自己實現flush()方法。
那麼,有人會問使用這種類的時候,難道必須使用flush()方法嗎,當然不是嘍??!!不過有個前提,你的字節數據必須不能小於8KB。實例代碼,注意沒有flush()方法。
- package mark.zhang;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- public class Test {
- public static void main(String[] args) throws Exception {
- File file = new File("text.txt");
- if(!file.exists()) {
- file.createNewFile();
- }
- FileOutputStream fos = new FileOutputStream(file);
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- byte[] b = new byte[1024*8];
- bos.write(b);
- //bos.flush();
- }
- }
執行代碼,會產生8KB的文本文件。當然,怎麼可能你每時每刻都知道你的數據一定會不小於8KB呢,所以還是調用flush()方法比較安全。不過,話又說回來,一般用完IO流之後(如果你有一個好的習慣)我們都會去調用close()方法,看源碼可以知道該方法也是調用相對應的flush()方法。所以,大多數情況下你不必要擔心。這裏提醒一下,如果你的文件讀寫沒有達到預期目的,十之八九是因爲你沒有調用flush()或者close()方法。
另外,字符流類大多數都實現了flush()或者close()方法,只不過,它們調用的是StreamEncoder類的該方法。該類位於sun.nio.cs包下面,其源碼在我們jdk中是沒有的。源碼地址:http://www.docjar.com/html/api/sun/nio/cs/StreamEncoder.java.html。在此,ctrl+v其源碼,如下:
- /*
- * Copyright 2001-2005 Sun Microsystems, Inc. All Rights Reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation. Sun designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Sun in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
- * CA 95054 USA or visit www.sun.com if you need additional information or
- * have any questions.
- */
- package sun.nio.cs;
- import java.io;
- import java.nio;
- import java.nio.channels;
- import java.nio.charset;
- public class StreamEncoder extends Writer
- {
- private static final int DEFAULT_BYTE_BUFFER_SIZE = 8192;
- private volatile boolean isOpen = true;
- private void ensureOpen() throws IOException {
- if (!isOpen)
- throw new IOException("Stream closed");
- }
- // Factories for java.io.OutputStreamWriter
- public static StreamEncoder forOutputStreamWriter(OutputStream out,
- Object lock,
- String charsetName)
- throws UnsupportedEncodingException
- {
- String csn = charsetName;
- if (csn == null)
- csn = Charset.defaultCharset().name();
- try {
- if (Charset.isSupported(csn))
- return new StreamEncoder(out, lock, Charset.forName(csn));
- } catch (IllegalCharsetNameException x) { }
- throw new UnsupportedEncodingException (csn);
- }
- public static StreamEncoder forOutputStreamWriter(OutputStream out,
- Object lock,
- Charset cs)
- {
- return new StreamEncoder(out, lock, cs);
- }
- public static StreamEncoder forOutputStreamWriter(OutputStream out,
- Object lock,
- CharsetEncoder enc)
- {
- return new StreamEncoder(out, lock, enc);
- }
- // Factory for java.nio.channels.Channels.newWriter
- public static StreamEncoder forEncoder(WritableByteChannel ch,
- CharsetEncoder enc,
- int minBufferCap)
- {
- return new StreamEncoder(ch, enc, minBufferCap);
- }
- // -- Public methods corresponding to those in OutputStreamWriter --
- // All synchronization and state/argument checking is done in these public
- // methods; the concrete stream-encoder subclasses defined below need not
- // do any such checking.
- public String getEncoding() {
- if (isOpen())
- return encodingName();
- return null;
- }
- public void flushBuffer() throws IOException {
- synchronized (lock) {
- if (isOpen())
- implFlushBuffer();
- else
- throw new IOException("Stream closed");
- }
- }
- public void write(int c) throws IOException {
- char cbuf[] = new char[1];
- cbuf[0] = (char) c;
- write(cbuf, 0, 1);
- }
- public void write(char cbuf[], int off, int len) throws IOException {
- synchronized (lock) {
- ensureOpen();
- if ((off < 0) || (off > cbuf.length) || (len < 0) ||
- ((off + len) > cbuf.length) || ((off + len) < 0)) {
- throw new IndexOutOfBoundsException();
- } else if (len == 0) {
- return;
- }
- implWrite(cbuf, off, len);
- }
- }
- public void write(String str, int off, int len) throws IOException {
- /* Check the len before creating a char buffer */
- if (len < 0)
- throw new IndexOutOfBoundsException();
- char cbuf[] = new char[len];
- str.getChars(off, off + len, cbuf, 0);
- write(cbuf, 0, len);
- }
- public void flush() throws IOException {
- synchronized (lock) {
- ensureOpen();
- implFlush();
- }
- }
- public void close() throws IOException {
- synchronized (lock) {
- if (!isOpen)
- return;
- implClose();
- isOpen = false;
- }
- }
- private boolean isOpen() {
- return isOpen;
- }
- // -- Charset-based stream encoder impl --
- private Charset cs;
- private CharsetEncoder encoder;
- private ByteBuffer bb;
- // Exactly one of these is non-null
- private final OutputStream out;
- private WritableByteChannel ch;
- // Leftover first char in a surrogate pair
- private boolean haveLeftoverChar = false;
- private char leftoverChar;
- private CharBuffer lcb = null;
- private StreamEncoder(OutputStream out, Object lock, Charset cs) {
- this(out, lock,
- cs.newEncoder()
- .onMalformedInput(CodingErrorAction.REPLACE)
- .onUnmappableCharacter(CodingErrorAction.REPLACE));
- }
- private StreamEncoder(OutputStream out, Object lock, CharsetEncoder enc) {
- super(lock);
- this.out = out;
- this.ch = null;
- this.cs = enc.charset();
- this.encoder = enc;
- // This path disabled until direct buffers are faster
- if (false && out instanceof FileOutputStream) {
- ch = ((FileOutputStream)out).getChannel();
- if (ch != null)
- bb = ByteBuffer.allocateDirect(DEFAULT_BYTE_BUFFER_SIZE);
- }
- if (ch == null) {
- bb = ByteBuffer.allocate(DEFAULT_BYTE_BUFFER_SIZE);
- }
- }
- private StreamEncoder(WritableByteChannel ch, CharsetEncoder enc, int mbc) {
- this.out = null;
- this.ch = ch;
- this.cs = enc.charset();
- this.encoder = enc;
- this.bb = ByteBuffer.allocate(mbc < 0
- ? DEFAULT_BYTE_BUFFER_SIZE
- : mbc);
- }
- private void writeBytes() throws IOException {
- bb.flip();
- int lim = bb.limit();
- int pos = bb.position();
- assert (pos <= lim);
- int rem = (pos <= lim ? lim - pos : 0);
- if (rem > 0) {
- if (ch != null) {
- if (ch.write(bb) != rem)
- assert false : rem;
- } else {
- out.write(bb.array(), bb.arrayOffset() + pos, rem);
- }
- }
- bb.clear();
- }
- private void flushLeftoverChar(CharBuffer cb, boolean endOfInput)
- throws IOException
- {
- if (!haveLeftoverChar && !endOfInput)
- return;
- if (lcb == null)
- lcb = CharBuffer.allocate(2);
- else
- lcb.clear();
- if (haveLeftoverChar)
- lcb.put(leftoverChar);
- if ((cb != null) && cb.hasRemaining())
- lcb.put(cb.get());
- lcb.flip();
- while (lcb.hasRemaining() || endOfInput) {
- CoderResult cr = encoder.encode(lcb, bb, endOfInput);
- if (cr.isUnderflow()) {
- if (lcb.hasRemaining()) {
- leftoverChar = lcb.get();
- if (cb != null && cb.hasRemaining())
- flushLeftoverChar(cb, endOfInput);
- return;
- }
- break;
- }
- if (cr.isOverflow()) {
- assert bb.position() > 0;
- writeBytes();
- continue;
- }
- cr.throwException();
- }
- haveLeftoverChar = false;
- }
- void implWrite(char cbuf[], int off, int len)
- throws IOException
- {
- CharBuffer cb = CharBuffer.wrap(cbuf, off, len);
- if (haveLeftoverChar)
- flushLeftoverChar(cb, false);
- while (cb.hasRemaining()) {
- CoderResult cr = encoder.encode(cb, bb, false);
- if (cr.isUnderflow()) {
- assert (cb.remaining() <= 1) : cb.remaining();
- if (cb.remaining() == 1) {
- haveLeftoverChar = true;
- leftoverChar = cb.get();
- }
- break;
- }
- if (cr.isOverflow()) {
- assert bb.position() > 0;
- writeBytes();
- continue;
- }
- cr.throwException();
- }
- }
- void implFlushBuffer() throws IOException {
- if (bb.position() > 0)
- writeBytes();
- }
- void implFlush() throws IOException {
- implFlushBuffer();
- if (out != null)
- out.flush();
- }
- void implClose() throws IOException {
- flushLeftoverChar(null, true);
- try {
- for (;;) {
- CoderResult cr = encoder.flush(bb);
- if (cr.isUnderflow())
- break;
- if (cr.isOverflow()) {
- assert bb.position() > 0;
- writeBytes();
- continue;
- }
- cr.throwException();
- }
- if (bb.position() > 0)
- writeBytes();
- if (ch != null)
- ch.close();
- else
- out.close();
- } catch (IOException x) {
- encoder.reset();
- throw x;
- }
- }
- String encodingName() {
- return ((cs instanceof HistoricallyNamedCharset)
- ? ((HistoricallyNamedCharset)cs).historicalName()
- : cs.name());
- }
更多源碼查看http://www.docjar.com/projects/Open-JDK-6.b17-src-code.html
2. Writer類的flush方法
該類是一個抽象類,聲明如下:
- public abstract class Writer implements Appendable, Closeable, Flushable
Writer類的flush()方法是一個抽象方法,其子類一般都實現了該方法。所以,一般使用字符流之後,調用一下flush()或者close()方法。
- abstract public void flush() throws IOException;
細節請看jdk的api,或者Java的源碼以及上面的StreamEncoder類源碼。
ok,說到這裏吧,這裏主要藉助Java的IO中字節流與字符流的flush()方法,來說明學Java看源碼和思考是很重要的。
總之,不管你使用哪種流(字符、字節、具有緩衝的流)技術,不妨調用一下flush()/close()方法,防止數據無法寫到輸出流中。