1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   *
12   *
13   */
14  
15  package com.liferay.portal.kernel.io;
16  
17  import com.liferay.portal.kernel.nio.charset.CharsetEncoderUtil;
18  import com.liferay.portal.kernel.util.StringPool;
19  
20  import java.io.IOException;
21  import java.io.OutputStream;
22  import java.io.Writer;
23  
24  import java.nio.ByteBuffer;
25  import java.nio.CharBuffer;
26  import java.nio.charset.CharsetEncoder;
27  
28  /**
29   * <a href="OutputStreamWriter.java.html"><b><i>View Source</i></b></a>
30   *
31   * @author Shuyang Zhou
32   */
33  public class OutputStreamWriter extends Writer {
34  
35      public OutputStreamWriter(OutputStream outputStream) {
36          this(outputStream, StringPool.UTF8);
37      }
38  
39      public OutputStreamWriter(OutputStream outputStream, String charsetName) {
40          _outputStream = outputStream;
41          _charsetName = charsetName;
42          _charsetEncoder = CharsetEncoderUtil.getCharsetEncoder(charsetName);
43      }
44  
45      public void close() throws IOException {
46          _outputStream.close();
47      }
48  
49      public void flush() throws IOException {
50          _outputStream.flush();
51      }
52  
53      public String getEncoding() {
54          return _charsetName;
55      }
56  
57      public void write(char[] charArray, int offset, int length)
58          throws IOException {
59  
60          ByteBuffer byteBuffer = _charsetEncoder.encode(
61              CharBuffer.wrap(charArray, offset, length));
62  
63          _outputStream.write(byteBuffer.array(), 0, byteBuffer.limit());
64      }
65  
66      public void write(int c) throws IOException {
67          ByteBuffer byteBuffer = _charsetEncoder.encode(
68              CharBuffer.wrap(new char[] {(char)c}));
69  
70          _outputStream.write(byteBuffer.array(), 0, byteBuffer.limit());
71      }
72  
73      public void write(String string, int offset, int length)
74          throws IOException {
75  
76          ByteBuffer byteBuffer = _charsetEncoder.encode(
77              CharBuffer.wrap(string, offset, length));
78  
79          _outputStream.write(byteBuffer.array(), 0, byteBuffer.limit());
80      }
81  
82      private CharsetEncoder _charsetEncoder;
83      private String _charsetName;
84      private OutputStream _outputStream;
85  
86  }