001
014
015 package com.liferay.portal.kernel.io;
016
017 import com.liferay.portal.kernel.nio.charset.CharsetEncoderUtil;
018 import com.liferay.portal.kernel.util.StringPool;
019
020 import java.io.IOException;
021 import java.io.OutputStream;
022 import java.io.Writer;
023
024 import java.nio.ByteBuffer;
025 import java.nio.CharBuffer;
026 import java.nio.charset.CharsetEncoder;
027
028
031 public class OutputStreamWriter extends Writer {
032
033 public OutputStreamWriter(OutputStream outputStream) {
034 this(outputStream, StringPool.UTF8);
035 }
036
037 public OutputStreamWriter(OutputStream outputStream, String charsetName) {
038 _outputStream = outputStream;
039 _charsetName = charsetName;
040 _charsetEncoder = CharsetEncoderUtil.getCharsetEncoder(charsetName);
041 }
042
043 public void close() throws IOException {
044 _outputStream.close();
045 }
046
047 public void flush() throws IOException {
048 _outputStream.flush();
049 }
050
051 public String getEncoding() {
052 return _charsetName;
053 }
054
055 public void write(char[] charArray, int offset, int length)
056 throws IOException {
057
058 ByteBuffer byteBuffer = _charsetEncoder.encode(
059 CharBuffer.wrap(charArray, offset, length));
060
061 _outputStream.write(byteBuffer.array(), 0, byteBuffer.limit());
062 }
063
064 public void write(int c) throws IOException {
065 ByteBuffer byteBuffer = _charsetEncoder.encode(
066 CharBuffer.wrap(new char[] {(char)c}));
067
068 _outputStream.write(byteBuffer.array(), 0, byteBuffer.limit());
069 }
070
071 public void write(String string, int offset, int length)
072 throws IOException {
073
074 ByteBuffer byteBuffer = _charsetEncoder.encode(
075 CharBuffer.wrap(string, offset, length));
076
077 _outputStream.write(byteBuffer.array(), 0, byteBuffer.limit());
078 }
079
080 private CharsetEncoder _charsetEncoder;
081 private String _charsetName;
082 private OutputStream _outputStream;
083
084 }