001
014
015 package com.liferay.portal.kernel.io.unsync;
016
017 import java.io.IOException;
018 import java.io.Writer;
019
020
027 public class UnsyncBufferedWriter extends Writer {
028
029 public UnsyncBufferedWriter(Writer writer) {
030 this(writer, _DEFAULT_BUFFER_SIZE);
031 }
032
033 public UnsyncBufferedWriter(Writer writer, int size) {
034 if (size <= 0) {
035 throw new IllegalArgumentException("Buffer size is less than 0");
036 }
037
038 this.writer = writer;
039 this.size = size;
040
041 buffer = new char[size];
042 }
043
044 public void close() throws IOException {
045 if (writer == null) {
046 return;
047 }
048
049 if (count > 0) {
050 writer.write(buffer, 0, count);
051
052 count = 0;
053 }
054
055 writer.flush();
056 writer.close();
057
058 writer = null;
059 buffer = null;
060 }
061
062 public void flush() throws IOException {
063 if (writer == null) {
064 throw new IOException("Writer is null");
065 }
066
067 if (count > 0) {
068 writer.write(buffer, 0, count);
069
070 count = 0;
071 }
072
073 writer.flush();
074 }
075
076 public void newLine() throws IOException {
077 write(_LINE_SEPARATOR);
078 }
079
080 public void write(char[] charArray, int offset, int length)
081 throws IOException {
082
083 if (writer == null) {
084 throw new IOException("Writer is null");
085 }
086
087 if (length >= size) {
088 if (count > 0) {
089 writer.write(buffer, 0, count);
090
091 count = 0;
092 }
093
094 writer.write(charArray, offset, length);
095
096 return;
097 }
098
099 if ((count > 0) && (length > (size - count))) {
100 writer.write(buffer, 0, count);
101
102 count = 0;
103 }
104
105 System.arraycopy(charArray, offset, buffer, count, length);
106
107 count += length;
108 }
109
110 public void write(int c) throws IOException {
111 if (writer == null) {
112 throw new IOException("Writer is null");
113 }
114
115 if (count >= size) {
116 writer.write(buffer);
117
118 count = 0;
119 }
120
121 buffer[count++] = (char)c;
122 }
123
124 public void write(String string, int offset, int length)
125 throws IOException {
126
127 if (writer == null) {
128 throw new IOException("Writer is null");
129 }
130
131 int x = offset;
132 int y = offset + length;
133
134 while (x < y) {
135 if (count >= size) {
136 writer.write(buffer);
137
138 count = 0;
139 }
140
141 int leftFreeSpace = size - count;
142 int leftDataSize = y - x;
143
144 if (leftFreeSpace > leftDataSize) {
145 string.getChars(x, y, buffer, count);
146
147 count += leftDataSize;
148
149 break;
150 }
151 else {
152 int copyEnd = x + leftFreeSpace;
153
154 string.getChars(x, copyEnd, buffer, count);
155
156 count += leftFreeSpace;
157
158 x = copyEnd;
159 }
160 }
161 }
162
163 protected char[] buffer;
164 protected int count;
165 protected int size;
166 protected Writer writer;
167
168 private static int _DEFAULT_BUFFER_SIZE = 8192;
169
170 private static String _LINE_SEPARATOR = System.getProperty(
171 "line.separator");
172
173 }