1 /*
  2  * Copyright (c) 1996, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.io;
 27 
 28 import java.nio.CharBuffer;
 29 import java.nio.charset.Charset;
 30 import java.nio.charset.CharsetEncoder;
 31 import sun.nio.cs.StreamEncoder;
 32 
 33 
 34 /**
 35  * An OutputStreamWriter is a bridge from character streams to byte streams:
 36  * Characters written to it are encoded into bytes using a specified {@link
 37  * Charset charset}.  The charset that it uses
 38  * may be specified by name or may be given explicitly, or the
 39  * default charset may be accepted.
 40  *
 41  * <p> Each invocation of a write() method causes the encoding converter to be
 42  * invoked on the given character(s).  The resulting bytes are accumulated in a
 43  * buffer before being written to the underlying output stream.  Note that the
 44  * characters passed to the write() methods are not buffered.
 45  *
 46  * <p> For top efficiency, consider wrapping an OutputStreamWriter within a
 47  * BufferedWriter so as to avoid frequent converter invocations.  For example:
 48  *
 49  * <pre>
 50  * Writer out
 51  *   = new BufferedWriter(new OutputStreamWriter(anOutputStream));
 52  * </pre>
 53  *
 54  * <p> A <i>surrogate pair</i> is a character represented by a sequence of two
 55  * {@code char} values: A <i>high</i> surrogate in the range '&#92;uD800' to
 56  * '&#92;uDBFF' followed by a <i>low</i> surrogate in the range '&#92;uDC00' to
 57  * '&#92;uDFFF'.
 58  *
 59  * <p> A <i>malformed surrogate element</i> is a high surrogate that is not
 60  * followed by a low surrogate or a low surrogate that is not preceded by a
 61  * high surrogate.
 62  *
 63  * <p> This class always replaces malformed surrogate elements and unmappable
 64  * character sequences with the charset's default <i>substitution sequence</i>.
 65  * The {@linkplain CharsetEncoder} class should be used when more
 66  * control over the encoding process is required.
 67  *
 68  * @see BufferedWriter
 69  * @see OutputStream
 70  * @see Charset
 71  *
 72  * @author      Mark Reinhold
 73  * @since       1.1
 74  */
 75 
 76 public class OutputStreamWriter extends Writer {
 77 
 78     private final StreamEncoder se;
 79 
 80     /**
 81      * Creates an OutputStreamWriter that uses the named charset.
 82      *
 83      * @param  out
 84      *         An OutputStream
 85      *
 86      * @param  charsetName
 87      *         The name of a supported {@link Charset charset}
 88      *
 89      * @throws     UnsupportedEncodingException
 90      *             If the named encoding is not supported
 91      */
 92     public OutputStreamWriter(OutputStream out, String charsetName)
 93         throws UnsupportedEncodingException
 94     {
 95         super(out);
 96         if (charsetName == null)
 97             throw new NullPointerException("charsetName");
 98         se = StreamEncoder.forOutputStreamWriter(out, this, charsetName);
 99     }
100 
101     /**
102      * Creates an OutputStreamWriter that uses the default character encoding, or
103      * where {@code out} is a {@code PrintStream}, the charset used by the print
104      * stream.
105      *
106      * @param  out  An OutputStream
107      * @see Charset#defaultCharset()
108      */
109     public OutputStreamWriter(OutputStream out) {
110         super(out);
111         se = StreamEncoder.forOutputStreamWriter(out, this,
112                 out instanceof PrintStream ps ? ps.charset() : Charset.defaultCharset());
113     }
114 
115     /**
116      * Creates an OutputStreamWriter that uses the given charset.
117      *
118      * @param  out
119      *         An OutputStream
120      *
121      * @param  cs
122      *         A charset
123      *
124      * @since 1.4
125      */
126     public OutputStreamWriter(OutputStream out, Charset cs) {
127         super(out);
128         if (cs == null)
129             throw new NullPointerException("charset");
130         se = StreamEncoder.forOutputStreamWriter(out, this, cs);
131     }
132 
133     /**
134      * Creates an OutputStreamWriter that uses the given charset encoder.
135      *
136      * @param  out
137      *         An OutputStream
138      *
139      * @param  enc
140      *         A charset encoder
141      *
142      * @since 1.4
143      */
144     public OutputStreamWriter(OutputStream out, CharsetEncoder enc) {
145         super(out);
146         if (enc == null)
147             throw new NullPointerException("charset encoder");
148         se = StreamEncoder.forOutputStreamWriter(out, this, enc);
149     }
150 
151     /**
152      * Returns the name of the character encoding being used by this stream.
153      *
154      * <p> If the encoding has an historical name then that name is returned;
155      * otherwise the encoding's canonical name is returned.
156      *
157      * <p> If this instance was created with the {@link
158      * #OutputStreamWriter(OutputStream, String)} constructor then the returned
159      * name, being unique for the encoding, may differ from the name passed to
160      * the constructor.  This method may return {@code null} if the stream has
161      * been closed. </p>
162      *
163      * @return The historical name of this encoding, or possibly
164      *         {@code null} if the stream has been closed
165      *
166      * @see Charset
167      *
168      * @revised 1.4
169      */
170     public String getEncoding() {
171         return se.getEncoding();
172     }
173 
174     /**
175      * Flushes the output buffer to the underlying byte stream, without flushing
176      * the byte stream itself.  This method is non-private only so that it may
177      * be invoked by PrintStream.
178      */
179     void flushBuffer() throws IOException {
180         se.flushBuffer();
181     }
182 
183     /**
184      * Writes a single character.
185      *
186      * @throws     IOException  If an I/O error occurs
187      */
188     public void write(int c) throws IOException {
189         se.write(c);
190     }
191 
192     /**
193      * Writes a portion of an array of characters.
194      *
195      * @param  cbuf  Buffer of characters
196      * @param  off   Offset from which to start writing characters
197      * @param  len   Number of characters to write
198      *
199      * @throws  IndexOutOfBoundsException
200      *          If {@code off} is negative, or {@code len} is negative,
201      *          or {@code off + len} is negative or greater than the length
202      *          of the given array
203      *
204      * @throws  IOException  If an I/O error occurs
205      */
206     public void write(char[] cbuf, int off, int len) throws IOException {
207         se.write(cbuf, off, len);
208     }
209 
210     /**
211      * Writes a portion of a string.
212      *
213      * @param  str  A String
214      * @param  off  Offset from which to start writing characters
215      * @param  len  Number of characters to write
216      *
217      * @throws  IndexOutOfBoundsException
218      *          If {@code off} is negative, or {@code len} is negative,
219      *          or {@code off + len} is negative or greater than the length
220      *          of the given string
221      *
222      * @throws  IOException  If an I/O error occurs
223      */
224     public void write(String str, int off, int len) throws IOException {
225         se.write(str, off, len);
226     }
227 
228     @Override
229     public Writer append(CharSequence csq, int start, int end) throws IOException {
230         if (csq == null) csq = "null";
231         return append(csq.subSequence(start, end));
232     }
233 
234     @Override
235     public Writer append(CharSequence csq) throws IOException {
236         if (csq instanceof CharBuffer) {
237             se.write((CharBuffer) csq);
238         } else {
239             se.write(String.valueOf(csq));
240         }
241         return this;
242     }
243 
244     /**
245      * Flushes the stream.
246      *
247      * @throws     IOException  If an I/O error occurs
248      */
249     public void flush() throws IOException {
250         se.flush();
251     }
252 
253     public void close() throws IOException {
254         se.close();
255     }
256 }