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 java.util.Objects;
 32 import sun.nio.cs.StreamEncoder;
 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     private final StreamEncoder se;
 78 
 79     /**
 80      * Creates an OutputStreamWriter that uses the named charset.
 81      *
 82      * @param  out
 83      *         An OutputStream
 84      *
 85      * @param  charsetName
 86      *         The name of a supported {@link Charset charset}
 87      *
 88      * @throws     UnsupportedEncodingException
 89      *             If the named encoding is not supported
 90      */
 91     public OutputStreamWriter(OutputStream out, String charsetName)
 92         throws UnsupportedEncodingException
 93     {
 94         Objects.requireNonNull(out);
 95         Objects.requireNonNull(charsetName, "charsetName");
 96         se = StreamEncoder.forOutputStreamWriter(out, lock, charsetName);
 97     }
 98 
 99     /**
100      * Creates an OutputStreamWriter that uses the default character encoding.
101      *
102      * @param  out  An OutputStream
103      * @see Charset#defaultCharset()
104      */
105     public OutputStreamWriter(OutputStream out) {
106         Objects.requireNonNull(out);
107         se = StreamEncoder.forOutputStreamWriter(out, lock, Charset.defaultCharset());
108     }
109 
110     /**
111      * Creates an OutputStreamWriter that uses the given charset.
112      *
113      * @param  out
114      *         An OutputStream
115      *
116      * @param  cs
117      *         A charset
118      *
119      * @since 1.4
120      */
121     public OutputStreamWriter(OutputStream out, Charset cs) {
122         Objects.requireNonNull(out);
123         Objects.requireNonNull(cs, "charset");
124         se = StreamEncoder.forOutputStreamWriter(out, lock, cs);
125     }
126 
127     /**
128      * Creates an OutputStreamWriter that uses the given charset encoder.
129      *
130      * @param  out
131      *         An OutputStream
132      *
133      * @param  enc
134      *         A charset encoder
135      *
136      * @since 1.4
137      */
138     public OutputStreamWriter(OutputStream out, CharsetEncoder enc) {
139         Objects.requireNonNull(out);
140         Objects.requireNonNull(enc, "charset encoder");
141         se = StreamEncoder.forOutputStreamWriter(out, lock, enc);
142     }
143 
144     /**
145      * Returns the name of the character encoding being used by this stream.
146      *
147      * <p> If the encoding has an historical name then that name is returned;
148      * otherwise the encoding's canonical name is returned.
149      *
150      * <p> If this instance was created with the {@link
151      * #OutputStreamWriter(OutputStream, String)} constructor then the returned
152      * name, being unique for the encoding, may differ from the name passed to
153      * the constructor.  This method may return {@code null} if the stream has
154      * been closed. </p>
155      *
156      * @return The historical name of this encoding, or possibly
157      *         {@code null} if the stream has been closed
158      *
159      * @see Charset
160      *
161      * @revised 1.4
162      */
163     public String getEncoding() {
164         return se.getEncoding();
165     }
166 
167     /**
168      * Flushes the output buffer to the underlying byte stream, without flushing
169      * the byte stream itself.  This method is non-private only so that it may
170      * be invoked by PrintStream.
171      */
172     void flushBuffer() throws IOException {
173         se.flushBuffer();
174     }
175 
176     /**
177      * Writes a single character.
178      *
179      * @throws     IOException  If an I/O error occurs
180      */
181     public void write(int c) throws IOException {
182         se.write(c);
183     }
184 
185     /**
186      * Writes a portion of an array of characters.
187      *
188      * @param  cbuf  Buffer of characters
189      * @param  off   Offset from which to start writing characters
190      * @param  len   Number of characters to write
191      *
192      * @throws  IndexOutOfBoundsException
193      *          If {@code off} is negative, or {@code len} is negative,
194      *          or {@code off + len} is negative or greater than the length
195      *          of the given array
196      *
197      * @throws  IOException  If an I/O error occurs
198      */
199     public void write(char[] cbuf, int off, int len) throws IOException {
200         se.write(cbuf, off, len);
201     }
202 
203     /**
204      * Writes a portion of a string.
205      *
206      * @param  str  A String
207      * @param  off  Offset from which to start writing characters
208      * @param  len  Number of characters to write
209      *
210      * @throws  IndexOutOfBoundsException
211      *          If {@code off} is negative, or {@code len} is negative,
212      *          or {@code off + len} is negative or greater than the length
213      *          of the given string
214      *
215      * @throws  IOException  If an I/O error occurs
216      */
217     public void write(String str, int off, int len) throws IOException {
218         se.write(str, off, len);
219     }
220 
221     @Override
222     public Writer append(CharSequence csq, int start, int end) throws IOException {
223         if (csq == null) csq = "null";
224         return append(csq.subSequence(start, end));
225     }
226 
227     @Override
228     public Writer append(CharSequence csq) throws IOException {
229         if (csq instanceof CharBuffer) {
230             se.write((CharBuffer) csq);
231         } else {
232             se.write(String.valueOf(csq));
233         }
234         return this;
235     }
236 
237     /**
238      * Flushes the stream.
239      *
240      * @throws     IOException  If an I/O error occurs
241      */
242     public void flush() throws IOException {
243         se.flush();
244     }
245 
246     public void close() throws IOException {
247         se.close();
248     }
249 }