< prev index next >

src/java.base/share/classes/java/io/Writer.java

Print this page

  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 


 29 import java.util.Objects;
 30 
 31 /**
 32  * Abstract class for writing to character streams.  The only methods that a
 33  * subclass must implement are write(char[], int, int), flush(), and close().
 34  * Most subclasses, however, will override some of the methods defined here in
 35  * order to provide higher efficiency, additional functionality, or both.
 36  *
 37  * @see   BufferedWriter
 38  * @see   CharArrayWriter
 39  * @see   FilterWriter
 40  * @see   OutputStreamWriter
 41  * @see   FileWriter
 42  * @see   PipedWriter
 43  * @see   PrintWriter
 44  * @see   StringWriter
 45  * @see Reader
 46  *
 47  * @author      Mark Reinhold
 48  * @since       1.1
 49  */
 50 
 51 public abstract class Writer implements Appendable, Closeable, Flushable {
 52 
 53     /**
 54      * Temporary buffer used to hold writes of strings and single characters
 55      */
 56     private char[] writeBuffer;
 57 
 58     /**
 59      * Size of writeBuffer, must be >= 1
 60      */
 61     private static final int WRITE_BUFFER_SIZE = 1024;
 62 
 63     /**
 64      * Returns a new {@code Writer} which discards all characters.  The
 65      * returned stream is initially open.  The stream is closed by calling
 66      * the {@code close()} method.  Subsequent calls to {@code close()} have
 67      * no effect.
 68      *
 69      * <p> While the stream is open, the {@code append(char)}, {@code
 70      * append(CharSequence)}, {@code append(CharSequence, int, int)},
 71      * {@code flush()}, {@code write(int)}, {@code write(char[])}, and
 72      * {@code write(char[], int, int)} methods do nothing. After the stream
 73      * has been closed, these methods all throw {@code IOException}.
 74      *
 75      * <p> The {@link #lock object} used to synchronize operations on the
 76      * returned {@code Writer} is not specified.
 77      *
 78      * @return a {@code Writer} which discards all characters
 79      *
 80      * @since 11
 81      */
 82     public static Writer nullWriter() {

142             public void close() throws IOException {
143                 closed = true;
144             }
145         };
146     }
147 
148     /**
149      * The object used to synchronize operations on this stream.  For
150      * efficiency, a character-stream object may use an object other than
151      * itself to protect critical sections.  A subclass should therefore use
152      * the object in this field rather than {@code this} or a synchronized
153      * method.
154      */
155     protected Object lock;
156 
157     /**
158      * Creates a new character-stream writer whose critical sections will
159      * synchronize on the writer itself.
160      */
161     protected Writer() {
162         this.lock = this;










163     }
164 
165     /**
166      * Creates a new character-stream writer whose critical sections will
167      * synchronize on the given object.
168      *
169      * @param  lock
170      *         Object to synchronize on
171      */
172     protected Writer(Object lock) {
173         if (lock == null) {
174             throw new NullPointerException();
175         }
176         this.lock = lock;
177     }
178 
179     /**
180      * Writes a single character.  The character to be written is contained in
181      * the 16 low-order bits of the given integer value; the 16 high-order bits
182      * are ignored.
183      *
184      * <p> Subclasses that intend to support efficient single-character output
185      * should override this method.
186      *
187      * @param  c
188      *         int specifying a character to be written
189      *
190      * @throws  IOException
191      *          If an I/O error occurs
192      */
193     public void write(int c) throws IOException {
194         synchronized (lock) {
195             if (writeBuffer == null){
196                 writeBuffer = new char[WRITE_BUFFER_SIZE];
197             }
198             writeBuffer[0] = (char) c;
199             write(writeBuffer, 0, 1);
200         }
201     }
202 
203     /**
204      * Writes an array of characters.
205      *
206      * @param  cbuf
207      *         Array of characters to be written
208      *
209      * @throws  IOException
210      *          If an I/O error occurs
211      */
212     public void write(char[] cbuf) throws IOException {
213         write(cbuf, 0, cbuf.length);
214     }
215 
216     /**
217      * Writes a portion of an array of characters.
218      *
219      * @param  cbuf
220      *         Array of characters

259      *
260      * @param  str
261      *         A String
262      *
263      * @param  off
264      *         Offset from which to start writing characters
265      *
266      * @param  len
267      *         Number of characters to write
268      *
269      * @throws  IndexOutOfBoundsException
270      *          Implementations should throw this exception
271      *          if {@code off} is negative, or {@code len} is negative,
272      *          or {@code off + len} is negative or greater than the length
273      *          of the given string
274      *
275      * @throws  IOException
276      *          If an I/O error occurs
277      */
278     public void write(String str, int off, int len) throws IOException {
279         synchronized (lock) {
280             char cbuf[];
281             if (len <= WRITE_BUFFER_SIZE) {
282                 if (writeBuffer == null) {
283                     writeBuffer = new char[WRITE_BUFFER_SIZE];
284                 }
285                 cbuf = writeBuffer;
286             } else {    // Don't permanently allocate very large buffers.
287                 cbuf = new char[len];
288             }
289             str.getChars(off, (off + len), cbuf, 0);
290             write(cbuf, 0, len);
291         }
292     }
293 
294     /**
295      * Appends the specified character sequence to this writer.
296      *
297      * <p> An invocation of this method of the form {@code out.append(csq)}
298      * behaves in exactly the same way as the invocation
299      *
300      * <pre>
301      *     out.write(csq.toString()) </pre>
302      *
303      * <p> Depending on the specification of {@code toString} for the
304      * character sequence {@code csq}, the entire sequence may not be
305      * appended. For instance, invoking the {@code toString} method of a
306      * character buffer will return a subsequence whose content depends upon
307      * the buffer's position and limit.
308      *
309      * @param  csq
310      *         The character sequence to append.  If {@code csq} is
311      *         {@code null}, then the four characters {@code "null"} are

  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 
 29 import jdk.internal.misc.InternalLock;
 30 
 31 import java.util.Objects;
 32 
 33 /**
 34  * Abstract class for writing to character streams.  The only methods that a
 35  * subclass must implement are write(char[], int, int), flush(), and close().
 36  * Most subclasses, however, will override some of the methods defined here in
 37  * order to provide higher efficiency, additional functionality, or both.
 38  *
 39  * @see   BufferedWriter
 40  * @see   CharArrayWriter
 41  * @see   FilterWriter
 42  * @see   OutputStreamWriter
 43  * @see   FileWriter
 44  * @see   PipedWriter
 45  * @see   PrintWriter
 46  * @see   StringWriter
 47  * @see Reader
 48  *
 49  * @author      Mark Reinhold
 50  * @since       1.1
 51  */
 52 
 53 public abstract class Writer implements Appendable, Closeable, Flushable {
 54 










 55     /**
 56      * Returns a new {@code Writer} which discards all characters.  The
 57      * returned stream is initially open.  The stream is closed by calling
 58      * the {@code close()} method.  Subsequent calls to {@code close()} have
 59      * no effect.
 60      *
 61      * <p> While the stream is open, the {@code append(char)}, {@code
 62      * append(CharSequence)}, {@code append(CharSequence, int, int)},
 63      * {@code flush()}, {@code write(int)}, {@code write(char[])}, and
 64      * {@code write(char[], int, int)} methods do nothing. After the stream
 65      * has been closed, these methods all throw {@code IOException}.
 66      *
 67      * <p> The {@link #lock object} used to synchronize operations on the
 68      * returned {@code Writer} is not specified.
 69      *
 70      * @return a {@code Writer} which discards all characters
 71      *
 72      * @since 11
 73      */
 74     public static Writer nullWriter() {

134             public void close() throws IOException {
135                 closed = true;
136             }
137         };
138     }
139 
140     /**
141      * The object used to synchronize operations on this stream.  For
142      * efficiency, a character-stream object may use an object other than
143      * itself to protect critical sections.  A subclass should therefore use
144      * the object in this field rather than {@code this} or a synchronized
145      * method.
146      */
147     protected Object lock;
148 
149     /**
150      * Creates a new character-stream writer whose critical sections will
151      * synchronize on the writer itself.
152      */
153     protected Writer() {
154         // use InternalLock for trusted classes
155         Class<?> clazz = getClass();
156         if (clazz == OutputStreamWriter.class
157                 || clazz == BufferedWriter.class
158                 || clazz == FileWriter.class
159                 || clazz == PrintWriter.class
160                 || clazz == sun.nio.cs.StreamEncoder.class) {
161             this.lock = new InternalLock();
162         } else {
163             this.lock = this;
164         }
165     }
166 
167     /**
168      * Creates a new character-stream writer whose critical sections will
169      * synchronize on the given object.
170      *
171      * @param  lock
172      *         Object to synchronize on
173      */
174     protected Writer(Object lock) {
175         this.lock = Objects.requireNonNull(lock);



176     }
177 
178     /**
179      * Writes a single character.  The character to be written is contained in
180      * the 16 low-order bits of the given integer value; the 16 high-order bits
181      * are ignored.
182      *
183      * <p> Subclasses that intend to support efficient single-character output
184      * should override this method.
185      *
186      * @param  c
187      *         int specifying a character to be written
188      *
189      * @throws  IOException
190      *          If an I/O error occurs
191      */
192     public void write(int c) throws IOException {
193         var writeBuffer = new char[1];
194         writeBuffer[0] = (char) c;
195         write(writeBuffer, 0, 1);




196     }
197 
198     /**
199      * Writes an array of characters.
200      *
201      * @param  cbuf
202      *         Array of characters to be written
203      *
204      * @throws  IOException
205      *          If an I/O error occurs
206      */
207     public void write(char[] cbuf) throws IOException {
208         write(cbuf, 0, cbuf.length);
209     }
210 
211     /**
212      * Writes a portion of an array of characters.
213      *
214      * @param  cbuf
215      *         Array of characters

254      *
255      * @param  str
256      *         A String
257      *
258      * @param  off
259      *         Offset from which to start writing characters
260      *
261      * @param  len
262      *         Number of characters to write
263      *
264      * @throws  IndexOutOfBoundsException
265      *          Implementations should throw this exception
266      *          if {@code off} is negative, or {@code len} is negative,
267      *          or {@code off + len} is negative or greater than the length
268      *          of the given string
269      *
270      * @throws  IOException
271      *          If an I/O error occurs
272      */
273     public void write(String str, int off, int len) throws IOException {
274         Objects.checkFromIndexSize(off, len, str.length());
275         char cbuf[] = new char[len];
276         str.getChars(off, (off + len), cbuf, 0);
277         write(cbuf, 0, len);









278     }
279 
280     /**
281      * Appends the specified character sequence to this writer.
282      *
283      * <p> An invocation of this method of the form {@code out.append(csq)}
284      * behaves in exactly the same way as the invocation
285      *
286      * <pre>
287      *     out.write(csq.toString()) </pre>
288      *
289      * <p> Depending on the specification of {@code toString} for the
290      * character sequence {@code csq}, the entire sequence may not be
291      * appended. For instance, invoking the {@code toString} method of a
292      * character buffer will return a subsequence whose content depends upon
293      * the buffer's position and limit.
294      *
295      * @param  csq
296      *         The character sequence to append.  If {@code csq} is
297      *         {@code null}, then the four characters {@code "null"} are
< prev index next >