printstream.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 624 行 · 第 1/2 页

JAVA
624
字号
/* * @(#)PrintStream.java	1.29 06/10/13 * * Copyright  1990-2008 Sun Microsystems, Inc. All Rights Reserved.   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER   *    * This program 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.    *    * This program 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 at /legal/license.txt).    *    * 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 or visit www.sun.com if you need additional   * information or have any questions.  * */package java.io;/** * A <code>PrintStream</code> adds functionality to another output stream, * namely the ability to print representations of various data values * conveniently.  Two other features are provided as well.  Unlike other output * streams, a <code>PrintStream</code> never throws an * <code>IOException</code>; instead, exceptional situations merely set an * internal flag that can be tested via the <code>checkError</code> method. * Optionally, a <code>PrintStream</code> can be created so as to flush * automatically; this means that the <code>flush</code> method is * automatically invoked after a byte array is written, one of the * <code>println</code> methods is invoked, or a newline character or byte * (<code>'\n'</code>) is written. * * <p> All characters printed by a <code>PrintStream</code> are converted into * bytes using the platform's default character encoding.  The <code>{@link * PrintWriter}</code> class should be used in situations that require writing * characters rather than bytes. * * @version    1.21, 00/02/02 * @author     Mark Reinhold * @since      JDK1.0 */public class PrintStream extends FilterOutputStream {    private boolean autoFlush = false;    private boolean trouble = false;    /**     * Track both the text- and character-output streams, so that their buffers     * can be flushed without flushing the entire stream.     */    private BufferedWriter textOut;    private OutputStreamWriter charOut;    /**     * Create a new print stream.  This stream will not flush automatically.     *     * @param  out        The output stream to which values and objects will be     *                    printed     *     * @see java.io.PrintWriter#PrintWriter(java.io.OutputStream)     */    public PrintStream(OutputStream out) {	this(out, false);    }    /* Initialization is factored into a private constructor (note the swapped     * parameters so that this one isn't confused with the public one) and a     * separate init method so that the following two public constructors can     * share code.  We use a separate init method so that the constructor that     * takes an encoding will throw an NPE for a null stream before it throws     * an UnsupportedEncodingException for an unsupported encoding.     */    private PrintStream(boolean autoFlush, OutputStream out)    {	super(out);	if (out == null)	    throw new NullPointerException("Null output stream");	this.autoFlush = autoFlush;    }    private void init(OutputStreamWriter osw) {	this.charOut = osw;	this.textOut = new BufferedWriter(osw);    }    /**     * Create a new print stream.     *     * @param  out        The output stream to which values and objects will be     *                    printed     * @param  autoFlush  A boolean; if true, the output buffer will be flushed     *                    whenever a byte array is written, one of the     *                    <code>println</code> methods is invoked, or a newline     *                    character or byte (<code>'\n'</code>) is written     *     * @see java.io.PrintWriter#PrintWriter(java.io.OutputStream, boolean)     */    public PrintStream(OutputStream out, boolean autoFlush) {	this(autoFlush, out);	init(new OutputStreamWriter(this));    }    /**     * Create a new print stream.     *     * @param  out        The output stream to which values and objects will be     *                    printed     * @param  autoFlush  A boolean; if true, the output buffer will be flushed     *                    whenever a byte array is written, one of the     *                    <code>println</code> methods is invoked, or a newline     *                    character or byte (<code>'\n'</code>) is written     * @param  encoding   The name of a supported     *                    <a href="../lang/package-summary.html#charenc">     *                    character encoding</a>     *     * @exception  UnsupportedEncodingException     *             If the named encoding is not supported     */    public PrintStream(OutputStream out, boolean autoFlush, String encoding)        throws UnsupportedEncodingException    {	this(autoFlush, out);	init(new OutputStreamWriter(this, encoding));    }    /** Check to make sure that the stream has not been closed */    private void ensureOpen() throws IOException {	if (out == null)	    throw new IOException("Stream closed");    }    /**     * Flush the stream.  This is done by writing any buffered output bytes to     * the underlying output stream and then flushing that stream.     *     * @see        java.io.OutputStream#flush()     */    public void flush() {	synchronized (this) {	    try {		ensureOpen();		out.flush();	    }	    catch (IOException x) {		trouble = true;	    }	}    }    private boolean closing = false; /* To avoid recursive closing */    /**     * Close the stream.  This is done by flushing the stream and then closing     * the underlying output stream.     *     * @see        java.io.OutputStream#close()     */    public void close() {	synchronized (this) {	    if (! closing) {		closing = true;		try {		    textOut.close();		    out.close();		}		catch (IOException x) {		    trouble = true;		}		textOut = null;		charOut = null;		out = null;	    }	}    }    /**     * Flush the stream and check its error state.  The internal error state     * is set to <code>true</code> when the underlying output stream throws an     * <code>IOException</code> other than <code>InterruptedIOException</code>,     * and when the <code>setError</code> method is invoked.  If an operation     * on the underlying output stream throws an     * <code>InterruptedIOException</code>, then the <code>PrintStream</code>     * converts the exception back into an interrupt by doing:     * <pre>     *     Thread.currentThread().interrupt();     * </pre>     * or the equivalent.     *     * @return True if and only if this stream has encountered an     *         <code>IOException</code> other than     *         <code>InterruptedIOException</code>, or the     *         <code>setError</code> method has been invoked     */    public boolean checkError() {	if (out != null)	    flush();	return trouble;    }    /**     * Set the error state of the stream to <code>true</code>.     *     * @since JDK1.1     */    protected void setError() {	trouble = true;    }    /*     * Exception-catching, synchronized output operations,     * which also implement the write() methods of OutputStream     */    /**     * Write the specified byte to this stream.  If the byte is a newline and     * automatic flushing is enabled then the <code>flush</code> method will be     * invoked.     *     * <p> Note that the byte is written as given; to write a character that     * will be translated according to the platform's default character     * encoding, use the <code>print(char)</code> or <code>println(char)</code>     * methods.     *     * @param  b  The byte to be written     * @see #print(char)     * @see #println(char)     */    public void write(int b) {	try {	    synchronized (this) {		ensureOpen();		out.write(b);		if ((b == '\n') && autoFlush)		    out.flush();	    }	}	catch (InterruptedIOException x) {	    Thread.currentThread().interrupt();	}	catch (IOException x) {	    trouble = true;	}    }    /**     * Write <code>len</code> bytes from the specified byte array starting at     * offset <code>off</code> to this stream.  If automatic flushing is     * enabled then the <code>flush</code> method will be invoked.     *     * <p> Note that the bytes will be written as given; to write characters     * that will be translated according to the platform's default character     * encoding, use the <code>print(char)</code> or <code>println(char)</code>     * methods.     *     * @param  buf   A byte array     * @param  off   Offset from which to start taking bytes     * @param  len   Number of bytes to write     */    public void write(byte buf[], int off, int len) {	try {	    synchronized (this) {		ensureOpen();		out.write(buf, off, len);		if (autoFlush)		    out.flush();	    }	}	catch (InterruptedIOException x) {	    Thread.currentThread().interrupt();	}	catch (IOException x) {	    trouble = true;	}    }    /*     * The following private methods on the text- and character-output streams     * always flush the stream buffers, so that writes to the underlying byte     * stream occur as promptly as with the original PrintStream.     */    private void write(char buf[]) {	try {	    synchronized (this) {		ensureOpen();		textOut.write(buf);		textOut.flushBuffer();		charOut.flushBuffer();		if (autoFlush) {		    for (int i = 0; i < buf.length; i++)			if (buf[i] == '\n')			    out.flush();		}	    }	}	catch (InterruptedIOException x) {	    Thread.currentThread().interrupt();	}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?