Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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.*;
 
 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 (!)
             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(outlock, Charset.forName(csn));
         } catch (IllegalCharsetNameException x) { }
         throw new UnsupportedEncodingException (csn);
     }
 
     public static StreamEncoder forOutputStreamWriter(OutputStream out,
                                                       Object lock,
                                                       Charset cs)
     {
         return new StreamEncoder(outlockcs);
     }
 
     public static StreamEncoder forOutputStreamWriter(OutputStream out,
                                                       Object lock,
                                                       CharsetEncoder enc)
     {
         return new StreamEncoder(outlockenc);
     }
 
 
     // Factory for java.nio.channels.Channels.newWriter
 
     public static StreamEncoder forEncoder(WritableByteChannel ch,
                                            CharsetEncoder enc,
                                            int minBufferCap)
     {
         return new StreamEncoder(chencminBufferCap);
     }
 
 
     // -- 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 () {
            if (isOpen())
                implFlushBuffer();
            else
                throw new IOException("Stream closed");
        }
    }
    public void write(int cthrows IOException {
        char cbuf[] = new char[1];
        cbuf[0] = (charc;
        write(cbuf, 0, 1);
    }
    public void write(char cbuf[], int offint lenthrows IOException {
        synchronized () {
            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(cbufofflen);
        }
    }
    public void write(String strint offint lenthrows IOException {
        /* Check the len before creating a char buffer */
        if (len < 0)
            throw new IndexOutOfBoundsException();
        char cbuf[] = new char[len];
        str.getChars(offoff + lencbuf, 0);
        write(cbuf, 0, len);
    }
    public void flush() throws IOException {
        synchronized () {
            ensureOpen();
            implFlush();
        }
    }
    public void close() throws IOException {
        synchronized () {
            if (!)
                return;
            implClose();
             = false;
        }
    }
    private boolean isOpen() {
        return ;
    }
    // -- 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 outObject lockCharset cs) {
        this(outlock,
         cs.newEncoder()
    }
    private StreamEncoder(OutputStream outObject lockCharsetEncoder enc) {
        super(lock);
        this. = out;
        this. = null;
        this. = enc.charset();
        this. = enc;
        // This path disabled until direct buffers are faster
        if (false && out instanceof FileOutputStream) {
                 = ((FileOutputStream)out).getChannel();
        if ( != null)
                     = ByteBuffer.allocateDirect();
        }
            if ( == null) {
         = ByteBuffer.allocate();
        }
    }
    private StreamEncoder(WritableByteChannel chCharsetEncoder encint mbc) {
        this. = null;
        this. = ch;
        this. = enc.charset();
        this. = enc;
        this. = ByteBuffer.allocate(mbc < 0
                                  ? 
                                  : mbc);
    }
    private void writeBytes() throws IOException {
        .flip();
        int lim = .limit();
        int pos = .position();
        assert (pos <= lim);
        int rem = (pos <= lim ? lim - pos : 0);
            if (rem > 0) {
        if ( != null) {
            if (.write() != rem)
                assert false : rem;
        } else {
            .write(.array(), .arrayOffset() + posrem);
        }
        }
        .clear();
        }
    private void flushLeftoverChar(CharBuffer cbboolean endOfInput)
        throws IOException
    {
        if (! && !endOfInput)
            return;
        if ( == null)
             = CharBuffer.allocate(2);
        else
            .clear();
        if ()
            .put();
        if ((cb != null) && cb.hasRemaining())
            .put(cb.get());
        .flip();
        while (.hasRemaining() || endOfInput) {
            CoderResult cr = .encode(endOfInput);
            if (cr.isUnderflow()) {
                if (.hasRemaining()) {
                     = .get();
                    if (cb != null && cb.hasRemaining())
                        flushLeftoverChar(cbendOfInput);
                    return;
                }
                break;
            }
            if (cr.isOverflow()) {
                assert .position() > 0;
                writeBytes();
                continue;
            }
            cr.throwException();
        }
         = false;
    }
    void implWrite(char cbuf[], int offint len)
        throws IOException
    {
        CharBuffer cb = CharBuffer.wrap(cbufofflen);
        if ()
        flushLeftoverChar(cbfalse);
        while (cb.hasRemaining()) {
        CoderResult cr = .encode(cbfalse);
        if (cr.isUnderflow()) {
           assert (cb.remaining() <= 1) : cb.remaining();
           if (cb.remaining() == 1) {
                 = true;
                 = cb.get();
            }
            break;
        }
        if (cr.isOverflow()) {
            assert .position() > 0;
            writeBytes();
            continue;
        }
        cr.throwException();
        }
    }
    void implFlushBuffer() throws IOException {
        if (.position() > 0)
        writeBytes();
    }
    void implFlush() throws IOException {
        implFlushBuffer();
        if ( != null)
        .flush();
    }
    void implClose() throws IOException {
        flushLeftoverChar(nulltrue);
        try {
            for (;;) {
                CoderResult cr = .flush();
                if (cr.isUnderflow())
                    break;
                if (cr.isOverflow()) {
                    assert .position() > 0;
                    writeBytes();
                    continue;
                }
                cr.throwException();
            }
            if (.position() > 0)
                writeBytes();
            if ( != null)
                .close();
            else
                .close();
        } catch (IOException x) {
            .reset();
            throw x;
        }
    }
    String encodingName() {
        return (( instanceof HistoricallyNamedCharset)
            ? ((HistoricallyNamedCharset)).historicalName()
            : .name());
    }
New to GrepCode? Check out our FAQ X